<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2006 Torus Knot Software Ltd
Also see acknowledgements in Readme.html

This program 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 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 Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.

You may alternatively use this source under the terms of a specific version of
the OGRE Unrestricted License provided you have obtained such a license from
Torus Knot Software Ltd.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreException.h"

#include "OgreRoot.h"
#include "OgreLogManager.h"

#ifdef __BORLANDC__
    #include <stdio.h>
#endif

namespace Ogre {

    Exception::Exception(int num, const String& desc, const String& src) :
        line( 0 ),
        number( num ),
        description( desc ),
        source( src )
    {
        // Log this error - not any more, allow catchers to do it
        //LogManager::getSingleton().logMessage(this->getFullDescription());
    }

    Exception::Exception(int num, const String& desc, const String& src,
		const char* typ, const char* fil, long lin) :
        line( lin ),
        number( num ),
		typeName(typ),
        description( desc ),
        source( src ),
        file( fil )
    {
        // Log this error, mask it from debug though since it may be caught and ignored
        if(LogManager::getSingletonPtr())
		{
            LogManager::getSingleton().logMessage(
				this->getFullDescription(),
                LML_CRITICAL, true);
		}

    }

    Exception::Exception(const Exception& rhs)
        : line( rhs.line ), number( rhs.number ), description( rhs.description ), source( rhs.source ), file( rhs.file )
    {
    }

    void Exception::operator = ( const Exception& rhs )
    {
        description = rhs.description;
        number = rhs.number;
        source = rhs.source;
        file = rhs.file;
        line = rhs.line;
		typeName = rhs.typeName;
    }

    const String& Exception::getFullDescription(void) const
    {
		if (fullDesc.empty())
		{

			StringUtil::StrStreamType desc;

			desc <<  "OGRE EXCEPTION(" << number << ":" << typeName << "): "
				<< description
				<< " in " << source;

			if( line > 0 )
			{
				desc << " at " << file << " (line " << line << ")";
			}

			fullDesc = desc.str();
		}

		return fullDesc;
    }

    int Exception::getNumber(void) const throw()
    {
        return number;
    }

}

<commit_msg>Patch 2460634: Fix uninitialised typeName in Exception copy constructor<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2006 Torus Knot Software Ltd
Also see acknowledgements in Readme.html

This program 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 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 Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.

You may alternatively use this source under the terms of a specific version of
the OGRE Unrestricted License provided you have obtained such a license from
Torus Knot Software Ltd.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreException.h"

#include "OgreRoot.h"
#include "OgreLogManager.h"

#ifdef __BORLANDC__
    #include <stdio.h>
#endif

namespace Ogre {

    Exception::Exception(int num, const String& desc, const String& src) :
        line( 0 ),
        number( num ),
        description( desc ),
        source( src )
    {
        // Log this error - not any more, allow catchers to do it
        //LogManager::getSingleton().logMessage(this->getFullDescription());
    }

    Exception::Exception(int num, const String& desc, const String& src,
		const char* typ, const char* fil, long lin) :
        line( lin ),
        number( num ),
		typeName(typ),
        description( desc ),
        source( src ),
        file( fil )
    {
        // Log this error, mask it from debug though since it may be caught and ignored
        if(LogManager::getSingletonPtr())
		{
            LogManager::getSingleton().logMessage(
				this->getFullDescription(),
                LML_CRITICAL, true);
		}

    }

    Exception::Exception(const Exception& rhs)
        : line( rhs.line ),
		number( rhs.number ),
		typeName( rhs.typeName ),
		description( rhs.description ),
		source( rhs.source ),
		file( rhs.file )
    {
    }

    void Exception::operator = ( const Exception& rhs )
    {
        description = rhs.description;
        number = rhs.number;
        source = rhs.source;
        file = rhs.file;
        line = rhs.line;
		typeName = rhs.typeName;
    }

    const String& Exception::getFullDescription(void) const
    {
		if (fullDesc.empty())
		{

			StringUtil::StrStreamType desc;

			desc <<  "OGRE EXCEPTION(" << number << ":" << typeName << "): "
				<< description
				<< " in " << source;

			if( line > 0 )
			{
				desc << " at " << file << " (line " << line << ")";
			}

			fullDesc = desc.str();
		}

		return fullDesc;
    }

    int Exception::getNumber(void) const throw()
    {
        return number;
    }

}

<|endoftext|>


<commit_before>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "kernel/yosys.h"
#include "kernel/sigtools.h"
#include "kernel/celltypes.h"

USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN

struct opts_t
{
	bool initeq = false;
	bool anyeq = false;
	bool fwd = false;
	bool bwd = false;
	bool nop = false;
};

struct FmcombineWorker
{
	const opts_t &opts;
	Design *design;
	Module *original = nullptr;
	Module *module = nullptr;
	IdString orig_type, combined_type;

	FmcombineWorker(Design *design, IdString orig_type, const opts_t &opts) :
			opts(opts), design(design), original(design->module(orig_type)),
			orig_type(orig_type), combined_type("$fmcombine" + orig_type.str())
	{
	}

	SigSpec import_sig(SigSpec sig, const string &suffix)
	{
		SigSpec newsig;
		for (auto chunk : sig.chunks()) {
			if (chunk.wire != nullptr)
				chunk.wire = module->wire(chunk.wire->name.str() + suffix);
			newsig.append(chunk);
		}
		return newsig;
	}

	Cell *import_prim_cell(Cell *cell, const string &suffix)
	{
		Cell *c = module->addCell(cell->name.str() + suffix, cell->type);
		c->parameters = cell->parameters;
		c->attributes = cell->attributes;

		for (auto &conn : cell->connections())
			c->setPort(conn.first, import_sig(conn.second, suffix));

		return c;
	}

	void import_hier_cell(Cell *cell)
	{
		if (!cell->parameters.empty())
			log_cmd_error("Cell %s.%s has unresolved instance parameters.\n", log_id(original), log_id(cell));

		FmcombineWorker sub_worker(design, cell->type, opts);
		sub_worker.generate();

		Cell *c = module->addCell(cell->name.str() + "_combined", sub_worker.combined_type);
		// c->parameters = cell->parameters;
		c->attributes = cell->attributes;

		for (auto &conn : cell->connections()) {
			c->setPort(conn.first.str() + "_gold", import_sig(conn.second, "_gold"));
			c->setPort(conn.first.str() + "_gate", import_sig(conn.second, "_gate"));
		}
	}

	void generate()
	{
		if (design->module(combined_type)) {
			// log("Combined module %s already exists.\n", log_id(combined_type));
			return;
		}

		log("Generating combined module %s from module %s.\n", log_id(combined_type), log_id(orig_type));
		module = design->addModule(combined_type);

		for (auto wire : original->wires()) {
			module->addWire(wire->name.str() + "_gold", wire);
			module->addWire(wire->name.str() + "_gate", wire);
		}
		module->fixup_ports();

		for (auto cell : original->cells()) {
			if (design->module(cell->type) == nullptr) {
				if (opts.anyeq && cell->type.in("$anyseq", "$anyconst")) {
					Cell *gold = import_prim_cell(cell, "_gold");
					for (auto &conn : cell->connections())
						module->connect(import_sig(conn.second, "_gate"), gold->getPort(conn.first));
				} else {
					Cell *gold = import_prim_cell(cell, "_gold");
					Cell *gate = import_prim_cell(cell, "_gate");
					if (opts.initeq) {
						if (cell->type.in("$ff", "$dff", "$dffe",
								"$dffsr", "$adff", "$dlatch", "$dlatchsr")) {
							SigSpec gold_q = gold->getPort("\\Q");
							SigSpec gate_q = gate->getPort("\\Q");
							SigSpec en = module->Initstate(NEW_ID);
							SigSpec eq = module->Eq(NEW_ID, gold_q, gate_q);
							module->addAssume(NEW_ID, eq, en);
						}
					}
				}
			} else {
				import_hier_cell(cell);
			}
		}

		for (auto &conn : original->connections()) {
			module->connect(import_sig(conn.first, "_gold"), import_sig(conn.second, "_gold"));
			module->connect(import_sig(conn.first, "_gate"), import_sig(conn.second, "_gate"));
		}

		if (opts.nop)
			return;

		CellTypes ct;
		ct.setup_internals_eval();
		ct.setup_stdcells_eval();

		SigMap sigmap(module);

		dict<SigBit, SigBit> data_bit_to_eq_net;
		dict<Cell*, SigSpec> cell_to_eq_nets;
		dict<SigSpec, SigSpec> reduce_db;
		dict<SigSpec, SigSpec> invert_db;

		for (auto cell : original->cells())
		{
			if (!ct.cell_known(cell->type))
				continue;

			for (auto &conn : cell->connections())
			{
				if (!cell->output(conn.first))
					continue;

				SigSpec A = import_sig(conn.second, "_gold");
				SigSpec B = import_sig(conn.second, "_gate");
				SigBit EQ = module->Eq(NEW_ID, A, B);

				for (auto bit : sigmap({A, B}))
					data_bit_to_eq_net[bit] = EQ;

				cell_to_eq_nets[cell].append(EQ);
			}
		}

		for (auto cell : original->cells())
		{
			if (!ct.cell_known(cell->type))
				continue;

			bool skip_cell = !cell_to_eq_nets.count(cell);
			pool<SigBit> src_eq_bits;

			for (auto &conn : cell->connections())
			{
				if (skip_cell)
					break;

				if (cell->output(conn.first))
					continue;

				SigSpec A = import_sig(conn.second, "_gold");
				SigSpec B = import_sig(conn.second, "_gate");

				for (auto bit : sigmap({A, B})) {
					if (data_bit_to_eq_net.count(bit))
						src_eq_bits.insert(data_bit_to_eq_net.at(bit));
					else
						skip_cell = true;
				}
			}

			if (!skip_cell) {
				SigSpec antecedent = SigSpec(src_eq_bits);
				antecedent.sort_and_unify();

				if (GetSize(antecedent) > 1) {
					if (reduce_db.count(antecedent) == 0)
						reduce_db[antecedent] = module->ReduceAnd(NEW_ID, antecedent);
					antecedent = reduce_db.at(antecedent);
				}

				SigSpec consequent = cell_to_eq_nets.at(cell);
				consequent.sort_and_unify();

				if (GetSize(consequent) > 1) {
					if (reduce_db.count(consequent) == 0)
						reduce_db[consequent] = module->ReduceAnd(NEW_ID, consequent);
					consequent = reduce_db.at(consequent);
				}

				if (opts.fwd)
					module->addAssume(NEW_ID, consequent, antecedent);

				if (opts.bwd)
				{
					if (invert_db.count(antecedent) == 0)
						invert_db[antecedent] = module->Not(NEW_ID, antecedent);

					if (invert_db.count(consequent) == 0)
						invert_db[consequent] = module->Not(NEW_ID, consequent);

					module->addAssume(NEW_ID, invert_db.at(antecedent), invert_db.at(consequent));
				}
			}
		}
	}
};

struct FmcombinePass : public Pass {
	FmcombinePass() : Pass("fmcombine", "combine two instances of a cell into one") { }
	void help() YS_OVERRIDE
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    fmcombine [options] module_name gold_cell gate_cell\n");
		// log("    fmcombine [options] @gold_cell @gate_cell\n");
		log("\n");
		log("This pass takes two cells, which are instances of the same module, and replaces\n");
		log("them with one instance of a special 'combined' module, that effectively\n");
		log("contains two copies of the original module, plus some formal properties.\n");
		log("\n");
		log("This is useful for formal test benches that check what differences in behavior\n");
		log("a slight difference in input causes in a module.\n");
		log("\n");
		log("    -initeq\n");
		log("        Insert assumptions that initially all FFs in both circuits have the\n");
		log("        same initial values.\n");
		log("\n");
		log("    -anyeq\n");
		log("        Do not duplicate $anyseq/$anyconst cells.\n");
		log("\n");
		log("    -fwd\n");
		log("        Insert forward hint assumptions into the combined module.\n");
		log("\n");
		log("    -bwd\n");
		log("        Insert backward hint assumptions into the combined module.\n");
		log("        (Backward hints are logically equivalend to fordward hits, but\n");
		log("        some solvers are faster with bwd hints, or even both -bwd and -fwd.)\n");
		log("\n");
		log("    -nop\n");
		log("        Don't insert hint assumptions into the combined module.\n");
		log("        (This should not provide any speedup over the original design, but\n");
		log("        strangely sometimes it does.)\n");
		log("\n");
		log("If none of -fwd, -bwd, and -nop is given, then -fwd is used as default.\n");
		log("\n");
	}
	void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
	{
		opts_t opts;
		Module *module = nullptr;
		Cell *gold_cell = nullptr;
		Cell *gate_cell = nullptr;

		log_header(design, "Executing FMCOMBINE pass.\n");

		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++)
		{
			// if (args[argidx] == "-o" && argidx+1 < args.size()) {
			// 	filename = args[++argidx];
			// 	continue;
			// }
			if (args[argidx] == "-initeq") {
				opts.initeq = true;
				continue;
			}
			if (args[argidx] == "-anyeq") {
				opts.anyeq = true;
				continue;
			}
			if (args[argidx] == "-fwd") {
				opts.fwd = true;
				continue;
			}
			if (args[argidx] == "-bwd") {
				opts.bwd = true;
				continue;
			}
			if (args[argidx] == "-nop") {
				opts.nop = true;
				continue;
			}
			break;
		}
		if (argidx+2 == args.size())
		{
			string gold_name = args[argidx++];
			string gate_name = args[argidx++];
			log_cmd_error("fmcombine @gold_cell @gate_cell call style is not implemented yet.");
		}
		else if (argidx+3 == args.size())
		{
			IdString module_name = RTLIL::escape_id(args[argidx++]);
			IdString gold_name = RTLIL::escape_id(args[argidx++]);
			IdString gate_name = RTLIL::escape_id(args[argidx++]);

			module = design->module(module_name);
			if (module == nullptr)
				log_cmd_error("Module %s not found.\n", log_id(module_name));

			gold_cell = module->cell(gold_name);
			if (gold_cell == nullptr)
				log_cmd_error("Gold cell %s not found in module %s.\n", log_id(gold_name), log_id(module));

			gate_cell = module->cell(gate_name);
			if (gate_cell == nullptr)
				log_cmd_error("Gold cell %s not found in module %s.\n", log_id(gate_name), log_id(module));
		}
		else
		{
			log_cmd_error("Invalid number of arguments.\n");
		}
		// extra_args(args, argidx, design);

		if (opts.nop && (opts.fwd || opts.bwd))
			log_cmd_error("Option -nop can not be combined with -fwd and/or -bwd.\n");

		if (!opts.nop && !opts.fwd && !opts.bwd)
			opts.fwd = true;

		if (gold_cell->type != gate_cell->type)
			log_cmd_error("Types of gold and gate cells do not match.\n");
		if (!gold_cell->parameters.empty())
			log_cmd_error("Gold cell has unresolved instance parameters.\n");
		if (!gate_cell->parameters.empty())
			log_cmd_error("Gold cell has unresolved instance parameters.\n");

		FmcombineWorker worker(design, gold_cell->type, opts);
		worker.generate();
		IdString combined_cell_name = module->uniquify(stringf("\\%s_%s", log_id(gold_cell), log_id(gate_cell)));

		Cell *cell = module->addCell(combined_cell_name, worker.combined_type);
		cell->attributes = gold_cell->attributes;
		cell->add_strpool_attribute("\\src", gate_cell->get_strpool_attribute("\\src"));

		log("Combining cells %s and %s in module %s into new cell %s.\n", log_id(gold_cell), log_id(gate_cell), log_id(module), log_id(cell));

		for (auto &conn : gold_cell->connections())
			cell->setPort(conn.first.str() + "_gold", conn.second);
		module->remove(gold_cell);

		for (auto &conn : gate_cell->connections())
			cell->setPort(conn.first.str() + "_gate", conn.second);
		module->remove(gate_cell);
	}
} FmcombinePass;

PRIVATE_NAMESPACE_END
<commit_msg>Fix typo in fmcombine log message, fixes #1063<commit_after>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "kernel/yosys.h"
#include "kernel/sigtools.h"
#include "kernel/celltypes.h"

USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN

struct opts_t
{
	bool initeq = false;
	bool anyeq = false;
	bool fwd = false;
	bool bwd = false;
	bool nop = false;
};

struct FmcombineWorker
{
	const opts_t &opts;
	Design *design;
	Module *original = nullptr;
	Module *module = nullptr;
	IdString orig_type, combined_type;

	FmcombineWorker(Design *design, IdString orig_type, const opts_t &opts) :
			opts(opts), design(design), original(design->module(orig_type)),
			orig_type(orig_type), combined_type("$fmcombine" + orig_type.str())
	{
	}

	SigSpec import_sig(SigSpec sig, const string &suffix)
	{
		SigSpec newsig;
		for (auto chunk : sig.chunks()) {
			if (chunk.wire != nullptr)
				chunk.wire = module->wire(chunk.wire->name.str() + suffix);
			newsig.append(chunk);
		}
		return newsig;
	}

	Cell *import_prim_cell(Cell *cell, const string &suffix)
	{
		Cell *c = module->addCell(cell->name.str() + suffix, cell->type);
		c->parameters = cell->parameters;
		c->attributes = cell->attributes;

		for (auto &conn : cell->connections())
			c->setPort(conn.first, import_sig(conn.second, suffix));

		return c;
	}

	void import_hier_cell(Cell *cell)
	{
		if (!cell->parameters.empty())
			log_cmd_error("Cell %s.%s has unresolved instance parameters.\n", log_id(original), log_id(cell));

		FmcombineWorker sub_worker(design, cell->type, opts);
		sub_worker.generate();

		Cell *c = module->addCell(cell->name.str() + "_combined", sub_worker.combined_type);
		// c->parameters = cell->parameters;
		c->attributes = cell->attributes;

		for (auto &conn : cell->connections()) {
			c->setPort(conn.first.str() + "_gold", import_sig(conn.second, "_gold"));
			c->setPort(conn.first.str() + "_gate", import_sig(conn.second, "_gate"));
		}
	}

	void generate()
	{
		if (design->module(combined_type)) {
			// log("Combined module %s already exists.\n", log_id(combined_type));
			return;
		}

		log("Generating combined module %s from module %s.\n", log_id(combined_type), log_id(orig_type));
		module = design->addModule(combined_type);

		for (auto wire : original->wires()) {
			module->addWire(wire->name.str() + "_gold", wire);
			module->addWire(wire->name.str() + "_gate", wire);
		}
		module->fixup_ports();

		for (auto cell : original->cells()) {
			if (design->module(cell->type) == nullptr) {
				if (opts.anyeq && cell->type.in("$anyseq", "$anyconst")) {
					Cell *gold = import_prim_cell(cell, "_gold");
					for (auto &conn : cell->connections())
						module->connect(import_sig(conn.second, "_gate"), gold->getPort(conn.first));
				} else {
					Cell *gold = import_prim_cell(cell, "_gold");
					Cell *gate = import_prim_cell(cell, "_gate");
					if (opts.initeq) {
						if (cell->type.in("$ff", "$dff", "$dffe",
								"$dffsr", "$adff", "$dlatch", "$dlatchsr")) {
							SigSpec gold_q = gold->getPort("\\Q");
							SigSpec gate_q = gate->getPort("\\Q");
							SigSpec en = module->Initstate(NEW_ID);
							SigSpec eq = module->Eq(NEW_ID, gold_q, gate_q);
							module->addAssume(NEW_ID, eq, en);
						}
					}
				}
			} else {
				import_hier_cell(cell);
			}
		}

		for (auto &conn : original->connections()) {
			module->connect(import_sig(conn.first, "_gold"), import_sig(conn.second, "_gold"));
			module->connect(import_sig(conn.first, "_gate"), import_sig(conn.second, "_gate"));
		}

		if (opts.nop)
			return;

		CellTypes ct;
		ct.setup_internals_eval();
		ct.setup_stdcells_eval();

		SigMap sigmap(module);

		dict<SigBit, SigBit> data_bit_to_eq_net;
		dict<Cell*, SigSpec> cell_to_eq_nets;
		dict<SigSpec, SigSpec> reduce_db;
		dict<SigSpec, SigSpec> invert_db;

		for (auto cell : original->cells())
		{
			if (!ct.cell_known(cell->type))
				continue;

			for (auto &conn : cell->connections())
			{
				if (!cell->output(conn.first))
					continue;

				SigSpec A = import_sig(conn.second, "_gold");
				SigSpec B = import_sig(conn.second, "_gate");
				SigBit EQ = module->Eq(NEW_ID, A, B);

				for (auto bit : sigmap({A, B}))
					data_bit_to_eq_net[bit] = EQ;

				cell_to_eq_nets[cell].append(EQ);
			}
		}

		for (auto cell : original->cells())
		{
			if (!ct.cell_known(cell->type))
				continue;

			bool skip_cell = !cell_to_eq_nets.count(cell);
			pool<SigBit> src_eq_bits;

			for (auto &conn : cell->connections())
			{
				if (skip_cell)
					break;

				if (cell->output(conn.first))
					continue;

				SigSpec A = import_sig(conn.second, "_gold");
				SigSpec B = import_sig(conn.second, "_gate");

				for (auto bit : sigmap({A, B})) {
					if (data_bit_to_eq_net.count(bit))
						src_eq_bits.insert(data_bit_to_eq_net.at(bit));
					else
						skip_cell = true;
				}
			}

			if (!skip_cell) {
				SigSpec antecedent = SigSpec(src_eq_bits);
				antecedent.sort_and_unify();

				if (GetSize(antecedent) > 1) {
					if (reduce_db.count(antecedent) == 0)
						reduce_db[antecedent] = module->ReduceAnd(NEW_ID, antecedent);
					antecedent = reduce_db.at(antecedent);
				}

				SigSpec consequent = cell_to_eq_nets.at(cell);
				consequent.sort_and_unify();

				if (GetSize(consequent) > 1) {
					if (reduce_db.count(consequent) == 0)
						reduce_db[consequent] = module->ReduceAnd(NEW_ID, consequent);
					consequent = reduce_db.at(consequent);
				}

				if (opts.fwd)
					module->addAssume(NEW_ID, consequent, antecedent);

				if (opts.bwd)
				{
					if (invert_db.count(antecedent) == 0)
						invert_db[antecedent] = module->Not(NEW_ID, antecedent);

					if (invert_db.count(consequent) == 0)
						invert_db[consequent] = module->Not(NEW_ID, consequent);

					module->addAssume(NEW_ID, invert_db.at(antecedent), invert_db.at(consequent));
				}
			}
		}
	}
};

struct FmcombinePass : public Pass {
	FmcombinePass() : Pass("fmcombine", "combine two instances of a cell into one") { }
	void help() YS_OVERRIDE
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    fmcombine [options] module_name gold_cell gate_cell\n");
		// log("    fmcombine [options] @gold_cell @gate_cell\n");
		log("\n");
		log("This pass takes two cells, which are instances of the same module, and replaces\n");
		log("them with one instance of a special 'combined' module, that effectively\n");
		log("contains two copies of the original module, plus some formal properties.\n");
		log("\n");
		log("This is useful for formal test benches that check what differences in behavior\n");
		log("a slight difference in input causes in a module.\n");
		log("\n");
		log("    -initeq\n");
		log("        Insert assumptions that initially all FFs in both circuits have the\n");
		log("        same initial values.\n");
		log("\n");
		log("    -anyeq\n");
		log("        Do not duplicate $anyseq/$anyconst cells.\n");
		log("\n");
		log("    -fwd\n");
		log("        Insert forward hint assumptions into the combined module.\n");
		log("\n");
		log("    -bwd\n");
		log("        Insert backward hint assumptions into the combined module.\n");
		log("        (Backward hints are logically equivalend to fordward hits, but\n");
		log("        some solvers are faster with bwd hints, or even both -bwd and -fwd.)\n");
		log("\n");
		log("    -nop\n");
		log("        Don't insert hint assumptions into the combined module.\n");
		log("        (This should not provide any speedup over the original design, but\n");
		log("        strangely sometimes it does.)\n");
		log("\n");
		log("If none of -fwd, -bwd, and -nop is given, then -fwd is used as default.\n");
		log("\n");
	}
	void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
	{
		opts_t opts;
		Module *module = nullptr;
		Cell *gold_cell = nullptr;
		Cell *gate_cell = nullptr;

		log_header(design, "Executing FMCOMBINE pass.\n");

		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++)
		{
			// if (args[argidx] == "-o" && argidx+1 < args.size()) {
			// 	filename = args[++argidx];
			// 	continue;
			// }
			if (args[argidx] == "-initeq") {
				opts.initeq = true;
				continue;
			}
			if (args[argidx] == "-anyeq") {
				opts.anyeq = true;
				continue;
			}
			if (args[argidx] == "-fwd") {
				opts.fwd = true;
				continue;
			}
			if (args[argidx] == "-bwd") {
				opts.bwd = true;
				continue;
			}
			if (args[argidx] == "-nop") {
				opts.nop = true;
				continue;
			}
			break;
		}
		if (argidx+2 == args.size())
		{
			string gold_name = args[argidx++];
			string gate_name = args[argidx++];
			log_cmd_error("fmcombine @gold_cell @gate_cell call style is not implemented yet.");
		}
		else if (argidx+3 == args.size())
		{
			IdString module_name = RTLIL::escape_id(args[argidx++]);
			IdString gold_name = RTLIL::escape_id(args[argidx++]);
			IdString gate_name = RTLIL::escape_id(args[argidx++]);

			module = design->module(module_name);
			if (module == nullptr)
				log_cmd_error("Module %s not found.\n", log_id(module_name));

			gold_cell = module->cell(gold_name);
			if (gold_cell == nullptr)
				log_cmd_error("Gold cell %s not found in module %s.\n", log_id(gold_name), log_id(module));

			gate_cell = module->cell(gate_name);
			if (gate_cell == nullptr)
				log_cmd_error("Gate cell %s not found in module %s.\n", log_id(gate_name), log_id(module));
		}
		else
		{
			log_cmd_error("Invalid number of arguments.\n");
		}
		// extra_args(args, argidx, design);

		if (opts.nop && (opts.fwd || opts.bwd))
			log_cmd_error("Option -nop can not be combined with -fwd and/or -bwd.\n");

		if (!opts.nop && !opts.fwd && !opts.bwd)
			opts.fwd = true;

		if (gold_cell->type != gate_cell->type)
			log_cmd_error("Types of gold and gate cells do not match.\n");
		if (!gold_cell->parameters.empty())
			log_cmd_error("Gold cell has unresolved instance parameters.\n");
		if (!gate_cell->parameters.empty())
			log_cmd_error("Gate cell has unresolved instance parameters.\n");

		FmcombineWorker worker(design, gold_cell->type, opts);
		worker.generate();
		IdString combined_cell_name = module->uniquify(stringf("\\%s_%s", log_id(gold_cell), log_id(gate_cell)));

		Cell *cell = module->addCell(combined_cell_name, worker.combined_type);
		cell->attributes = gold_cell->attributes;
		cell->add_strpool_attribute("\\src", gate_cell->get_strpool_attribute("\\src"));

		log("Combining cells %s and %s in module %s into new cell %s.\n", log_id(gold_cell), log_id(gate_cell), log_id(module), log_id(cell));

		for (auto &conn : gold_cell->connections())
			cell->setPort(conn.first.str() + "_gold", conn.second);
		module->remove(gold_cell);

		for (auto &conn : gate_cell->connections())
			cell->setPort(conn.first.str() + "_gate", conn.second);
		module->remove(gate_cell);
	}
} FmcombinePass;

PRIVATE_NAMESPACE_END
<|endoftext|>


<commit_before>#pragma once

#include <string>
#include <typeindex>

#include "blackhole/dynamic.hpp"

namespace blackhole {

template<typename T>
struct config_traits {
    //! \brief Statically maps sink or formatter type into unique key.
    /*! It contains information about its backends and strategies.
        For example: file sink with rotation is mapped into: `files/rotate`.
        Without rotation it will be just: `files`.
    */
    static std::string name() {
        return T::name();
    }
};

template<typename T>
struct match_traits {
    static bool matched(const std::string& type, const dynamic_t&) {
        return type == T::name();
    }

    static std::type_index ti(const std::string&, const dynamic_t&) {
        return typeid(T);
    }
};

} // namespace blackhole
<commit_msg>[Code Clean] Another pack of dead code.<commit_after>#pragma once

#include <string>
#include <typeindex>

#include "blackhole/dynamic.hpp"

namespace blackhole {

template<typename T>
struct config_traits {
    //! \brief Statically maps sink or formatter type into unique key.
    /*! It contains information about its backends and strategies.
        For example: file sink with rotation is mapped into: `files/rotate`.
        Without rotation it will be just: `files`.
    */
    static std::string name() {
        return T::name();
    }
};

template<typename T>
struct match_traits {
    static std::type_index ti(const std::string&, const dynamic_t&) {
        return typeid(T);
    }
};

} // namespace blackhole
<|endoftext|>


<commit_before>enum anaModes {mLocal,mLocalPAR,mPROOF,mGRID};
//mLocal: Analyze locally files in your computer using aliroot
//mLocalPAR: Analyze locally files in your computer using root + PAR files
//mPROOF: Analyze CAF files with PROOF

// RUN SETTINGS

// Flow analysis method can be:(set to kTRUE or kFALSE)
Bool_t SP       = kTRUE;
Bool_t LYZ1SUM  = kTRUE;
Bool_t LYZ1PROD = kTRUE;
Bool_t LYZ2SUM  = kFALSE;
Bool_t LYZ2PROD = kFALSE;
Bool_t LYZEP    = kFALSE;
Bool_t GFC      = kTRUE;
Bool_t QC       = kTRUE;
Bool_t FQD      = kTRUE;
Bool_t MCEP     = kTRUE; //not for pp

Bool_t METHODS[] = {SP,LYZ1SUM,LYZ1PROD,LYZ2SUM,LYZ2PROD,LYZEP,GFC,QC,FQD,MCEP};

// Analysis type can be ESD, AOD, MC, ESDMC0, ESDMC1
const TString type = "ESD";

// Boolean to fill/not fill the QA histograms
Bool_t QA = kTRUE;

// Boolean to use/not use weights for the Q vector
Bool_t WEIGHTS[] = {kFALSE,kFALSE,kFALSE}; //Phi, v'(pt), v'(eta)

//void runFlowTask(Int_t mode=mLocal, Int_t nRuns = 100,
		 //const Char_t* dataDir="/data/alice2/kolk/PP/LHC09a4/81119", Int_t offset = 0)
		 //const Char_t* dataDir="/data/alice2/kolk/Therminator_midcentral", Int_t offset = 0)
		 //const Char_t* dataDir="/Users/snelling/alice_data/Therminator_midcentral", Int_t offset = 0)
void runFlowTask(Int_t mode=mPROOF, Int_t nRuns = 100000,
		 //const Char_t* dataDir="/COMMON/COMMON/LHC09a14_0.9TeV_0.5T", Int_t offset = 0)
		 const Char_t* dataDir="/PWG2/akisiel/Therminator_midcentral_ESD", Int_t offset=0)
                 //const Char_t* dataDir="/COMMON/COMMON/LHC09a4_run8158X", Int_t offset = 0)

{
  TStopwatch timer;
  timer.Start();

  LoadLibraries(mode);

  if (mode==mLocal || mode == mLocalPAR || mode == mGRID) {
    if (type!="AOD") { TChain* chain = CreateESDChain(dataDir, nRuns, offset);}
    else { TChain* chain = CreateAODChain(dataDir, nRuns, offset);}
  }
  //____________________________________________//
  // Make the analysis manager
  AliAnalysisManager *mgr = new AliAnalysisManager("FlowAnalysisManager");

  if (type == "ESD"){
    AliVEventHandler* esdH = new AliESDInputHandler;
    mgr->SetInputEventHandler(esdH);

    AliMCEventHandler *mc = new AliMCEventHandler();
    mgr->SetMCtruthEventHandler(mc);
  }

  if (type == "AOD"){
    AliVEventHandler* aodH = new AliAODInputHandler;
    mgr->SetInputEventHandler(aodH);

    AliMCEventHandler *mc = new AliMCEventHandler();
    mgr->SetMCtruthEventHandler(mc);
  }

  if (type == "MC" || type == "ESDMC0" || type == "ESDMC1"){
    AliVEventHandler* esdH = new AliESDInputHandler;
    mgr->SetInputEventHandler(esdH);

    AliMCEventHandler *mc = new AliMCEventHandler();
    mgr->SetMCtruthEventHandler(mc);
  }

  //____________________________________________//
  // Load the tasks
  gROOT->LoadMacro("AddTaskFlow.C");
  AliAnalysisTaskFlowEvent* taskFE = AddTaskFlow(type,METHODS,QA,WEIGHTS);

  //____________________________________________//
  // Run the analysis
  if (!mgr->InitAnalysis()) return;
  mgr->PrintStatus();

  if (mode==mLocal || mode == mLocalPAR) {
    mgr->StartAnalysis("local",chain);
  }
  else if (mode==mPROOF) {
    mgr->StartAnalysis("proof",dataDir,nRuns,offset);
  }
  else if (mode==mGRID) {
    mgr->StartAnalysis("local",chain);
  }

  timer.Stop();
  timer.Print();

}

void LoadLibraries(const anaModes mode) {

  //--------------------------------------
  // Load the needed libraries most of them already loaded by aliroot
  //--------------------------------------
  gSystem->Load("libTree.so");
  gSystem->Load("libGeom.so");
  gSystem->Load("libVMC.so");
  gSystem->Load("libXMLIO.so");
  gSystem->Load("libPhysics.so");

  //----------------------------------------------------------
  // >>>>>>>>>>> Local mode <<<<<<<<<<<<<<
  //----------------------------------------------------------
  if (mode==mLocal) {
    //--------------------------------------------------------
    // If you want to use already compiled libraries
    // in the aliroot distribution
    //--------------------------------------------------------
    gSystem->Load("libSTEERBase");
    gSystem->Load("libESD");
    gSystem->Load("libAOD");
    gSystem->Load("libANALYSIS");
    gSystem->Load("libANALYSISalice");
    gSystem->Load("libCORRFW.so");
    cerr<<"libCORRFW.so loaded..."<<endl;
    gSystem->Load("libPWG2flowCommon.so");
    cerr<<"libPWG2flowCommon.so loaded..."<<endl;
    gSystem->Load("libPWG2flowTasks.so");
    cerr<<"libPWG2flowTasks.so loaded..."<<endl;
  }

  else if (mode == mLocalPAR || mode == mGRID) {
    //--------------------------------------------------------
    //If you want to use root and par files from aliroot
    //--------------------------------------------------------
    SetupPar("STEERBase");
    SetupPar("ESD");
    SetupPar("AOD");
    SetupPar("ANALYSIS");
    SetupPar("ANALYSISalice");
    SetupPar("PWG2AOD");
    SetupPar("CORRFW");
    SetupPar("PWG2flowCommon");
    cerr<<"PWG2flowCommon.par loaded..."<<endl;
    SetupPar("PWG2flowTasks");
    cerr<<"PWG2flowTasks.par loaded..."<<endl;
  }

  //---------------------------------------------------------
  // <<<<<<<<<< PROOF mode >>>>>>>>>>>>
  //---------------------------------------------------------
  else if (mode==mPROOF) {
    //

    //  set to debug root versus if needed
    //TProof::Mgr("alicecaf")->SetROOTVersion("v5-24-00a_dbg");
    //TProof::Mgr("alicecaf")->SetROOTVersion("v5-24-00a");

    // Connect to proof
    // Put appropriate username here
    // TProof::Reset("proof://snelling@alicecaf.cern.ch");
    printf("*** Connect to PROOF ***\n");
    //  TProof::Open("abilandz@alicecaf.cern.ch");
    //    TProof::Open("nkolk@alicecaf.cern.ch");
    TProof::Open("snelling@localhost");
	// list the data available
	//  gProof->ShowDataSets("/*/*");

    // Enable the STEERBase Package
    gProof->ClearPackage("STEERBase.par");
    gProof->UploadPackage("STEERBase.par");
    gProof->EnablePackage("STEERBase");
    // Enable the ESD Package
    gProof->ClearPackage("ESD.par");
    gProof->UploadPackage("ESD.par");
    gProof->EnablePackage("ESD");
    // Enable the AOD Package
    gProof->ClearPackage("AOD.par");
    gProof->UploadPackage("AOD.par");
    gProof->EnablePackage("AOD");
    // Enable the Analysis Package
    gProof->ClearPackage("ANALYSIS.par");
    gProof->UploadPackage("ANALYSIS.par");
    gProof->EnablePackage("ANALYSIS");
    // Enable the Analysis Package alice
    gProof->ClearPackage("ANALYSISalice.par");
    gProof->UploadPackage("ANALYSISalice.par");
    gProof->EnablePackage("ANALYSISalice");
    // Load the PWG2 AOD
    gProof->ClearPackage("PWG2AOD.par");
    gProof->UploadPackage("PWG2AOD.par");
    gProof->EnablePackage("PWG2AOD");
    // Enable the Correction Framework
    gProof->ClearPackage("CORRFW.par");
    gProof->UploadPackage("CORRFW.par");
    gProof->EnablePackage("CORRFW");
    // Enable Flow Analysis
    gProof->ClearPackage("PWG2flowCommon");
    gProof->UploadPackage("PWG2flowCommon.par");
    gProof->EnablePackage("PWG2flowCommon");
    gProof->ClearPackage("PWG2flowTasks");
    gProof->UploadPackage("PWG2flowTasks.par");
    gProof->EnablePackage("PWG2flowTasks");
    //
    gProof->ShowEnabledPackages();
  }

}

void SetupPar(char* pararchivename) {
  //Load par files, create analysis libraries
  //For testing, if par file already decompressed and modified
  //classes then do not decompress.

  TString cdir(Form("%s", gSystem->WorkingDirectory() )) ;
  TString parpar(Form("%s.par", pararchivename)) ;
  if ( gSystem->AccessPathName(parpar.Data()) ) {
    gSystem->ChangeDirectory(gSystem->Getenv("ALICE_ROOT")) ;
    TString processline(Form(".! make %s", parpar.Data())) ;
    gROOT->ProcessLine(processline.Data()) ;
    gSystem->ChangeDirectory(cdir) ;
    processline = Form(".! mv /tmp/%s .", parpar.Data()) ;
    gROOT->ProcessLine(processline.Data()) ;
  }
  if ( gSystem->AccessPathName(pararchivename) ) {
    TString processline = Form(".! tar xvzf %s",parpar.Data()) ;
    gROOT->ProcessLine(processline.Data());
  }

  TString ocwd = gSystem->WorkingDirectory();
  gSystem->ChangeDirectory(pararchivename);

  // check for BUILD.sh and execute
  if (!gSystem->AccessPathName("PROOF-INF/BUILD.sh")) {
    printf("*******************************\n");
    printf("*** Building PAR archive    ***\n");
    cout<<pararchivename<<endl;
    printf("*******************************\n");
    if (gSystem->Exec("PROOF-INF/BUILD.sh")) {
      Error("runProcess","Cannot Build the PAR Archive! - Abort!");
      return -1;
    }
  }
  // check for SETUP.C and execute
  if (!gSystem->AccessPathName("PROOF-INF/SETUP.C")) {
    printf("*******************************\n");
    printf("*** Setup PAR archive       ***\n");
    cout<<pararchivename<<endl;
    printf("*******************************\n");
    gROOT->Macro("PROOF-INF/SETUP.C");
  }

  gSystem->ChangeDirectory(ocwd.Data());
  printf("Current dir: %s\n", ocwd.Data());
}

// Helper macros for creating chains
// from: CreateESDChain.C,v 1.10 jgrosseo Exp

TChain* CreateESDChain(const char* aDataDir, Int_t aRuns, Int_t offset)
{
  // creates chain of files in a given directory or file containing a list.
  // In case of directory the structure is expected as:
  // <aDataDir>/<dir0>/AliESDs.root
  // <aDataDir>/<dir1>/AliESDs.root
  // ...

  if (!aDataDir)
    return 0;

  Long_t id, size, flags, modtime;
  if (gSystem->GetPathInfo(aDataDir, &id, &size, &flags, &modtime))
    {
      printf("%s not found.\n", aDataDir);
      return 0;
    }

  TChain* chain = new TChain("esdTree");
  TChain* chaingAlice = 0;

  if (flags & 2)
    {
      TString execDir(gSystem->pwd());
      TSystemDirectory* baseDir = new TSystemDirectory(".", aDataDir);
      TList* dirList            = baseDir->GetListOfFiles();
      Int_t nDirs               = dirList->GetEntries();
      gSystem->cd(execDir);

      Int_t count = 0;

      for (Int_t iDir=0; iDir<nDirs; ++iDir)
	{
	  TSystemFile* presentDir = (TSystemFile*) dirList->At(iDir);
	  if (!presentDir || !presentDir->IsDirectory() || strcmp(presentDir->GetName(), ".") == 0 || strcmp(presentDir->GetName(), "..") == 0)
	    continue;

	  if (offset > 0)
	    {
	      --offset;
	      continue;
	    }

	  if (count++ == aRuns)
	    break;

	  TString presentDirName(aDataDir);
	  presentDirName += "/";
	  presentDirName += presentDir->GetName();
	  chain->Add(presentDirName + "/AliESDs.root/esdTree");
	  //  cerr<<presentDirName<<endl;
	}

    }
  else
    {
      // Open the input stream
      ifstream in;
      in.open(aDataDir);

      Int_t count = 0;

      // Read the input list of files and add them to the chain
      TString esdfile;
      while(in.good()) {
	in >> esdfile;
	if (!esdfile.Contains("root")) continue; // protection

	if (offset > 0)
	  {
	    --offset;
	    continue;
	  }

	if (count++ == aRuns)
	  break;

	// add esd file
	chain->Add(esdfile);
      }

      in.close();
    }

  return chain;
}

// Helper macros for creating chains
// from: CreateESDChain.C,v 1.10 jgrosseo Exp

TChain* CreateAODChain(const char* aDataDir, Int_t aRuns, Int_t offset)
{
  // creates chain of files in a given directory or file containing a list.
  // In case of directory the structure is expected as:
  // <aDataDir>/<dir0>/AliAOD.root
  // <aDataDir>/<dir1>/AliAOD.root
  // ...

  if (!aDataDir)
    return 0;

  Long_t id, size, flags, modtime;
  if (gSystem->GetPathInfo(aDataDir, &id, &size, &flags, &modtime))
    {
      printf("%s not found.\n", aDataDir);
      return 0;
    }

  TChain* chain = new TChain("aodTree");
  TChain* chaingAlice = 0;

  if (flags & 2)
    {
      TString execDir(gSystem->pwd());
      TSystemDirectory* baseDir = new TSystemDirectory(".", aDataDir);
      TList* dirList            = baseDir->GetListOfFiles();
      Int_t nDirs               = dirList->GetEntries();
      gSystem->cd(execDir);

      Int_t count = 0;

      for (Int_t iDir=0; iDir<nDirs; ++iDir)
	{
	  TSystemFile* presentDir = (TSystemFile*) dirList->At(iDir);
	  if (!presentDir || !presentDir->IsDirectory() || strcmp(presentDir->GetName(), ".") == 0 || strcmp(presentDir->GetName(), "..") == 0)
	    continue;

	  if (offset > 0)
	    {
	      --offset;
	      continue;
	    }

	  if (count++ == aRuns)
	    break;

	  TString presentDirName(aDataDir);
	  presentDirName += "/";
	  presentDirName += presentDir->GetName();
	  chain->Add(presentDirName + "/AliAOD.root/aodTree");
	  // cerr<<presentDirName<<endl;
	}

    }
  else
    {
      // Open the input stream
      ifstream in;
      in.open(aDataDir);

      Int_t count = 0;

      // Read the input list of files and add them to the chain
      TString aodfile;
      while(in.good()) {
	in >> aodfile;
	if (!aodfile.Contains("root")) continue; // protection

	if (offset > 0)
	  {
	    --offset;
	    continue;
	  }

	if (count++ == aRuns)
	  break;

	// add aod file
	chain->Add(aodfile);
      }

      in.close();
    }

  return chain;
}

<commit_msg>reorganize ClearPackage, UploadPackage EnablePackage<commit_after>enum anaModes {mLocal,mLocalPAR,mPROOF,mGRID};
//mLocal: Analyze locally files in your computer using aliroot
//mLocalPAR: Analyze locally files in your computer using root + PAR files
//mPROOF: Analyze CAF files with PROOF

// RUN SETTINGS

// Flow analysis method can be:(set to kTRUE or kFALSE)
Bool_t SP       = kTRUE;
Bool_t LYZ1SUM  = kTRUE;
Bool_t LYZ1PROD = kTRUE;
Bool_t LYZ2SUM  = kFALSE;
Bool_t LYZ2PROD = kFALSE;
Bool_t LYZEP    = kFALSE;
Bool_t GFC      = kTRUE;
Bool_t QC       = kTRUE;
Bool_t FQD      = kTRUE;
Bool_t MCEP     = kTRUE; //not for pp

Bool_t METHODS[] = {SP,LYZ1SUM,LYZ1PROD,LYZ2SUM,LYZ2PROD,LYZEP,GFC,QC,FQD,MCEP};

// Analysis type can be ESD, AOD, MC, ESDMC0, ESDMC1
const TString type = "ESD";

// Boolean to fill/not fill the QA histograms
Bool_t QA = kTRUE;

// Boolean to use/not use weights for the Q vector
Bool_t WEIGHTS[] = {kFALSE,kFALSE,kFALSE}; //Phi, v'(pt), v'(eta)

//void runFlowTask(Int_t mode=mLocal, Int_t nRuns = 100,
		 //const Char_t* dataDir="/data/alice2/kolk/PP/LHC09a4/81119", Int_t offset = 0)
		 //const Char_t* dataDir="/data/alice2/kolk/Therminator_midcentral", Int_t offset = 0)
		 //const Char_t* dataDir="/Users/snelling/alice_data/Therminator_midcentral", Int_t offset = 0)
void runFlowTask(Int_t mode=mPROOF, Int_t nRuns = 1000000,
		 //const Char_t* dataDir="/COMMON/COMMON/LHC09a14_0.9TeV_0.5T", Int_t offset = 0)
		 //const Char_t* dataDir="/COMMON/COMMON/LHC08c11_10TeV_0.5T", Int_t offset = 0)
		 //const Char_t* dataDir="/PWG2/akisiel/Therminator_midcentral_ESD", Int_t offset=0)
                 const Char_t* dataDir="/COMMON/COMMON/LHC09a4_run8101X", Int_t offset = 0)

{
  TStopwatch timer;
  timer.Start();

  LoadLibraries(mode);

  if (mode==mLocal || mode == mLocalPAR || mode == mGRID) {
    if (type!="AOD") { TChain* chain = CreateESDChain(dataDir, nRuns, offset);}
    else { TChain* chain = CreateAODChain(dataDir, nRuns, offset);}
  }
  //____________________________________________//
  // Make the analysis manager
  AliAnalysisManager *mgr = new AliAnalysisManager("FlowAnalysisManager");

  if (type == "ESD"){
    AliVEventHandler* esdH = new AliESDInputHandler;
    mgr->SetInputEventHandler(esdH);

    AliMCEventHandler *mc = new AliMCEventHandler();
    mgr->SetMCtruthEventHandler(mc);
  }

  if (type == "AOD"){
    AliVEventHandler* aodH = new AliAODInputHandler;
    mgr->SetInputEventHandler(aodH);

    AliMCEventHandler *mc = new AliMCEventHandler();
    mgr->SetMCtruthEventHandler(mc);
  }

  if (type == "MC" || type == "ESDMC0" || type == "ESDMC1"){
    AliVEventHandler* esdH = new AliESDInputHandler;
    mgr->SetInputEventHandler(esdH);

    AliMCEventHandler *mc = new AliMCEventHandler();
    mgr->SetMCtruthEventHandler(mc);
  }

  //____________________________________________//
  // Load the tasks
  gROOT->LoadMacro("AddTaskFlow.C");
  AliAnalysisTaskFlowEvent* taskFE = AddTaskFlow(type,METHODS,QA,WEIGHTS);

  //____________________________________________//
  // Run the analysis
  if (!mgr->InitAnalysis()) return;
  mgr->PrintStatus();

  if (mode==mLocal || mode == mLocalPAR) {
    mgr->StartAnalysis("local",chain);
  }
  else if (mode==mPROOF) {
    mgr->StartAnalysis("proof",dataDir,nRuns,offset);
  }
  else if (mode==mGRID) {
    mgr->StartAnalysis("local",chain);
  }

  timer.Stop();
  timer.Print();

}

void LoadLibraries(const anaModes mode) {

  //--------------------------------------
  // Load the needed libraries most of them already loaded by aliroot
  //--------------------------------------
  gSystem->Load("libTree.so");
  gSystem->Load("libGeom.so");
  gSystem->Load("libVMC.so");
  gSystem->Load("libXMLIO.so");
  gSystem->Load("libPhysics.so");

  //----------------------------------------------------------
  // >>>>>>>>>>> Local mode <<<<<<<<<<<<<<
  //----------------------------------------------------------
  if (mode==mLocal) {
    //--------------------------------------------------------
    // If you want to use already compiled libraries
    // in the aliroot distribution
    //--------------------------------------------------------
    gSystem->Load("libSTEERBase");
    gSystem->Load("libESD");
    gSystem->Load("libAOD");
    gSystem->Load("libANALYSIS");
    gSystem->Load("libANALYSISalice");
    gSystem->Load("libCORRFW.so");
    cerr<<"libCORRFW.so loaded..."<<endl;
    gSystem->Load("libPWG2flowCommon.so");
    cerr<<"libPWG2flowCommon.so loaded..."<<endl;
    gSystem->Load("libPWG2flowTasks.so");
    cerr<<"libPWG2flowTasks.so loaded..."<<endl;
  }

  else if (mode == mLocalPAR || mode == mGRID) {
    //--------------------------------------------------------
    //If you want to use root and par files from aliroot
    //--------------------------------------------------------
    SetupPar("STEERBase");
    SetupPar("ESD");
    SetupPar("AOD");
    SetupPar("ANALYSIS");
    SetupPar("ANALYSISalice");
    SetupPar("PWG2AOD");
    SetupPar("CORRFW");
    SetupPar("PWG2flowCommon");
    cerr<<"PWG2flowCommon.par loaded..."<<endl;
    SetupPar("PWG2flowTasks");
    cerr<<"PWG2flowTasks.par loaded..."<<endl;
  }

  //---------------------------------------------------------
  // <<<<<<<<<< PROOF mode >>>>>>>>>>>>
  //---------------------------------------------------------
  else if (mode==mPROOF) {
    //

    //  set to debug root versus if needed
    //TProof::Mgr("alicecaf")->SetROOTVersion("v5-24-00a_dbg");
    //TProof::Mgr("alicecaf")->SetROOTVersion("v5-24-00a");

    //TProof::Reset("proof://snelling@alicecaf.cern.ch");
    // Connect to proof
    printf("*** Connect to PROOF ***\n");
    // Put appropriate username here
    //TProof::Open("abilandz@alicecaf.cern.ch");
    //TProof::Open("nkolk@alicecaf.cern.ch");
    TProof::Open("snelling@localhost");
    // list the data available
    //gProof->ShowDataSets("/*/*");

    // Clear the Packages
    gProof->ClearPackage("STEERBase.par");
    gProof->ClearPackage("ESD.par");
    gProof->ClearPackage("AOD.par");
    gProof->ClearPackage("ANALYSIS.par");
    gProof->ClearPackage("ANALYSISalice.par");
    gProof->ClearPackage("PWG2AOD.par");
    gProof->ClearPackage("CORRFW.par");
    gProof->ClearPackage("PWG2flowCommon");
    gProof->ClearPackage("PWG2flowTasks");

    // Upload the Packages
    gProof->UploadPackage("STEERBase.par");
    gProof->UploadPackage("ESD.par");
    gProof->UploadPackage("AOD.par");
    gProof->UploadPackage("ANALYSIS.par");
    gProof->UploadPackage("ANALYSISalice.par");
    gProof->UploadPackage("PWG2AOD.par");
    gProof->UploadPackage("CORRFW.par");
    gProof->UploadPackage("PWG2flowCommon.par");
    gProof->UploadPackage("PWG2flowTasks.par");

    // Enable the Packages
    gProof->EnablePackage("STEERBase");
    gProof->EnablePackage("ESD");
    gProof->EnablePackage("AOD");
    gProof->EnablePackage("ANALYSIS");
    gProof->EnablePackage("ANALYSISalice");
    gProof->EnablePackage("PWG2AOD");
    gProof->EnablePackage("CORRFW");
    gProof->EnablePackage("PWG2flowCommon");
    gProof->EnablePackage("PWG2flowTasks");

    // Show enables Packages
    gProof->ShowEnabledPackages();
  }

}

void SetupPar(char* pararchivename) {
  //Load par files, create analysis libraries
  //For testing, if par file already decompressed and modified
  //classes then do not decompress.

  TString cdir(Form("%s", gSystem->WorkingDirectory() )) ;
  TString parpar(Form("%s.par", pararchivename)) ;
  if ( gSystem->AccessPathName(parpar.Data()) ) {
    gSystem->ChangeDirectory(gSystem->Getenv("ALICE_ROOT")) ;
    TString processline(Form(".! make %s", parpar.Data())) ;
    gROOT->ProcessLine(processline.Data()) ;
    gSystem->ChangeDirectory(cdir) ;
    processline = Form(".! mv /tmp/%s .", parpar.Data()) ;
    gROOT->ProcessLine(processline.Data()) ;
  }
  if ( gSystem->AccessPathName(pararchivename) ) {
    TString processline = Form(".! tar xvzf %s",parpar.Data()) ;
    gROOT->ProcessLine(processline.Data());
  }

  TString ocwd = gSystem->WorkingDirectory();
  gSystem->ChangeDirectory(pararchivename);

  // check for BUILD.sh and execute
  if (!gSystem->AccessPathName("PROOF-INF/BUILD.sh")) {
    printf("*******************************\n");
    printf("*** Building PAR archive    ***\n");
    cout<<pararchivename<<endl;
    printf("*******************************\n");
    if (gSystem->Exec("PROOF-INF/BUILD.sh")) {
      Error("runProcess","Cannot Build the PAR Archive! - Abort!");
      return -1;
    }
  }
  // check for SETUP.C and execute
  if (!gSystem->AccessPathName("PROOF-INF/SETUP.C")) {
    printf("*******************************\n");
    printf("*** Setup PAR archive       ***\n");
    cout<<pararchivename<<endl;
    printf("*******************************\n");
    gROOT->Macro("PROOF-INF/SETUP.C");
  }

  gSystem->ChangeDirectory(ocwd.Data());
  printf("Current dir: %s\n", ocwd.Data());
}

// Helper macros for creating chains
// from: CreateESDChain.C,v 1.10 jgrosseo Exp

TChain* CreateESDChain(const char* aDataDir, Int_t aRuns, Int_t offset)
{
  // creates chain of files in a given directory or file containing a list.
  // In case of directory the structure is expected as:
  // <aDataDir>/<dir0>/AliESDs.root
  // <aDataDir>/<dir1>/AliESDs.root
  // ...

  if (!aDataDir)
    return 0;

  Long_t id, size, flags, modtime;
  if (gSystem->GetPathInfo(aDataDir, &id, &size, &flags, &modtime))
    {
      printf("%s not found.\n", aDataDir);
      return 0;
    }

  TChain* chain = new TChain("esdTree");
  TChain* chaingAlice = 0;

  if (flags & 2)
    {
      TString execDir(gSystem->pwd());
      TSystemDirectory* baseDir = new TSystemDirectory(".", aDataDir);
      TList* dirList            = baseDir->GetListOfFiles();
      Int_t nDirs               = dirList->GetEntries();
      gSystem->cd(execDir);

      Int_t count = 0;

      for (Int_t iDir=0; iDir<nDirs; ++iDir)
	{
	  TSystemFile* presentDir = (TSystemFile*) dirList->At(iDir);
	  if (!presentDir || !presentDir->IsDirectory() || strcmp(presentDir->GetName(), ".") == 0 || strcmp(presentDir->GetName(), "..") == 0)
	    continue;

	  if (offset > 0)
	    {
	      --offset;
	      continue;
	    }

	  if (count++ == aRuns)
	    break;

	  TString presentDirName(aDataDir);
	  presentDirName += "/";
	  presentDirName += presentDir->GetName();
	  chain->Add(presentDirName + "/AliESDs.root/esdTree");
	  //  cerr<<presentDirName<<endl;
	}

    }
  else
    {
      // Open the input stream
      ifstream in;
      in.open(aDataDir);

      Int_t count = 0;

      // Read the input list of files and add them to the chain
      TString esdfile;
      while(in.good()) {
	in >> esdfile;
	if (!esdfile.Contains("root")) continue; // protection

	if (offset > 0)
	  {
	    --offset;
	    continue;
	  }

	if (count++ == aRuns)
	  break;

	// add esd file
	chain->Add(esdfile);
      }

      in.close();
    }

  return chain;
}

// Helper macros for creating chains
// from: CreateESDChain.C,v 1.10 jgrosseo Exp

TChain* CreateAODChain(const char* aDataDir, Int_t aRuns, Int_t offset)
{
  // creates chain of files in a given directory or file containing a list.
  // In case of directory the structure is expected as:
  // <aDataDir>/<dir0>/AliAOD.root
  // <aDataDir>/<dir1>/AliAOD.root
  // ...

  if (!aDataDir)
    return 0;

  Long_t id, size, flags, modtime;
  if (gSystem->GetPathInfo(aDataDir, &id, &size, &flags, &modtime))
    {
      printf("%s not found.\n", aDataDir);
      return 0;
    }

  TChain* chain = new TChain("aodTree");
  TChain* chaingAlice = 0;

  if (flags & 2)
    {
      TString execDir(gSystem->pwd());
      TSystemDirectory* baseDir = new TSystemDirectory(".", aDataDir);
      TList* dirList            = baseDir->GetListOfFiles();
      Int_t nDirs               = dirList->GetEntries();
      gSystem->cd(execDir);

      Int_t count = 0;

      for (Int_t iDir=0; iDir<nDirs; ++iDir)
	{
	  TSystemFile* presentDir = (TSystemFile*) dirList->At(iDir);
	  if (!presentDir || !presentDir->IsDirectory() || strcmp(presentDir->GetName(), ".") == 0 || strcmp(presentDir->GetName(), "..") == 0)
	    continue;

	  if (offset > 0)
	    {
	      --offset;
	      continue;
	    }

	  if (count++ == aRuns)
	    break;

	  TString presentDirName(aDataDir);
	  presentDirName += "/";
	  presentDirName += presentDir->GetName();
	  chain->Add(presentDirName + "/AliAOD.root/aodTree");
	  // cerr<<presentDirName<<endl;
	}

    }
  else
    {
      // Open the input stream
      ifstream in;
      in.open(aDataDir);

      Int_t count = 0;

      // Read the input list of files and add them to the chain
      TString aodfile;
      while(in.good()) {
	in >> aodfile;
	if (!aodfile.Contains("root")) continue; // protection

	if (offset > 0)
	  {
	    --offset;
	    continue;
	  }

	if (count++ == aRuns)
	  break;

	// add aod file
	chain->Add(aodfile);
      }

      in.close();
    }

  return chain;
}

<|endoftext|>


<commit_before>#if !defined(__CINT__) || defined(__MAKECINT__)
#include <iostream>

#include "AliBWTools.h"
#include "AliBWFunc.h"
#include "AliLatexTable.h"
#include "TF1.h"
#include "TFile.h"
#include "TH1.h"
#include "TROOT.h"
#include "TDatabasePDG.h"
#include "TCanvas.h"
#include "TMath.h"
#include "TSystem.h"
#include "THashList.h"
#include "TMinuit.h"

using namespace std;
#endif

enum {kFitExpPt, kFitLevi};

void FitParticle(const char * file, const char * histo, const char * partName,  Float_t min = 0, Float_t max =3, Float_t scaleHisto = -1., Int_t fitFunc = kFitLevi, Int_t vartype = AliBWFunc::kdNdpt) {

  // Generic Macro to fit any particle using the PWG2/SPECTRA/Fit macros
  //
  // You have to provide:
  // - file: file name
  // - histo: histogram name name (assumend to be in the mail folder of the file)
  // - partName: it is used to get the mass of the particle from
  //   TDatabasePDG. If you are not sure, just use a part of the name: a
  //   list of names matching it is printed on screen
  //
  // You can optionally provide:
  // - min, max: the fit range
  // - scaleHisto: a scaling factor for the histo. If negative, it is
  //   ignored. If the histo is scaled, the bin width is also
  //   divided).
  // - fitFunc: id of the function, levi is the default
  // - varType: the variable used in the pt spectrum (see AliBWFunc.h)

  // load stuff
  gSystem->Load("libTree.so");
  gSystem->Load("libVMC.so");
  gSystem->Load("libMinuit.so");
  gSystem->Load("libSTEERBase.so");
  gSystem->Load("libESD.so");
  gSystem->Load("libAOD.so");
  gSystem->Load("libANALYSIS.so");
  gSystem->Load("libANALYSISalice.so");
  gSystem->Load("libCORRFW.so");
  gSystem->Load("libPWG2spectra.so");

  // get histo and draw
  AliBWFunc * fm = new AliBWFunc;
  fm->SetVarType(AliBWFunc::VarType_t(vartype));
  //  fm->SetVarType(AliBWFunc::VarType_t(0));//FIXME
  //  cout << "Warning: hacked vartype" << endl;

  if (!TDatabasePDG::Instance()->GetParticle(partName)) {
    cout << "Wrong particle name " << partName << endl;

    const THashList * l = TDatabasePDG::Instance()->ParticleList();
    Int_t npart = l->GetSize();
    for(Int_t ipart = 0; ipart < npart; ipart++){
      TString name = l->At(ipart)->GetName();
      if(name.Contains(partName, TString::kIgnoreCase))
	cout << " - Did you mean [" << name.Data() << "] ?" << endl;
    }

    cout << "Try [ TDatabasePDG::Instance()->GetParticle(partName) ] by hand "<< endl;
    return;

  }
  Double_t mass = TDatabasePDG::Instance()->GetParticle(partName)->Mass();
  TF1* func = 0;
  Int_t normPar = -1;
  if (fitFunc == kFitLevi)   {
    func = fm->GetLevi (mass, 0.2, 20,100);
    normPar = 0;
  }
  if (fitFunc == kFitExpPt)  {
    func = fm->GetPTExp(0.2, 20);
  }

  TFile * f = new TFile(file);
  TH1 * h = (TH1*) gDirectory->Get(histo); //
  h->Sumw2();
  if (scaleHisto > 0) h->Scale(scaleHisto, "width");
//   TH1 * h = AliBWTools::GetdNdPtFromOneOverPt((TH1*) gDirectory->Get(histo)); // FIXME
//   cout << "WARNING SCALING2PI" << endl;
//   h->Scale(2*TMath::Pi());//Fixme

//   h->Fit(func); // FIXME
//   gMinuit->Command("SET STRATEGY 2"); // FIXME

  if (!AliBWTools::Fit(h,func,min,max)) {
    cout << "Fitting error!" << endl;
    return;
  }

  TCanvas * c = new TCanvas();
  c->SetLogy();
  h->Draw();
  func->Draw("same");

  // Print results nicely
  AliLatexTable table(9,"c|ccccccc");
  table.InsertCustomRow("Part & Yield & T Slope & n & $\\Chi^2$/NDF & Min X & Frac Above & \\langle p_{t} \\rangle  & \\langle p_{t}^{2} \\rangle");
  // populate table
  Float_t yield  = func->Integral(0,100);
  Float_t yieldE = func->IntegralError(0,100);
//   Float_t yield  = func->Integral(0.45,1.05);
//   Float_t yieldE = func->IntegralError(0.45,1.05);
  Double_t tslope   = func->GetParameter(2);
  Double_t tslopeE = func->GetParError(2);

  table.SetNextCol(partName);
  table.SetNextCol(yield,yieldE,-4);
  table.SetNextCol(tslope,tslopeE,-4);
  table.SetNextCol(func->GetParameter(1),func->GetParError(1),-4);
  table.SetNextCol(Form("%2.2f/%d",func->GetChisquare(),func->GetNDF()));
  Float_t lowestPoint = TMath::Max(AliBWTools::GetLowestNotEmptyBinEdge(h),min);
  Float_t yieldAbove  = func->Integral(lowestPoint,100);
  table.SetNextCol(lowestPoint,-2);
  table.SetNextCol(yieldAbove/yield,-2);
  Float_t mean, meane;
  Float_t mean2, mean2e;
  AliBWTools::GetMean      (func, mean,  meane , 0.,100., normPar);
  AliBWTools::GetMeanSquare(func, mean2, mean2e, 0.,100., normPar);
  table.SetNextCol(mean,  meane ,-4);
  table.SetNextCol(mean2, mean2e,-4);
  //			 fMean2->IntegralError(0,100)/func->Integral(0,100),-7);
  table.InsertRow();
  table.PrintTable("ASCII");

}
<commit_msg>Changed label in the fit results table<commit_after>#if !defined(__CINT__) || defined(__MAKECINT__)
#include <iostream>

#include "AliBWTools.h"
#include "AliBWFunc.h"
#include "AliLatexTable.h"
#include "TF1.h"
#include "TFile.h"
#include "TH1.h"
#include "TROOT.h"
#include "TDatabasePDG.h"
#include "TCanvas.h"
#include "TMath.h"
#include "TSystem.h"
#include "THashList.h"
#include "TMinuit.h"

using namespace std;
#endif

enum {kFitExpPt, kFitLevi};

void FitParticle(const char * file, const char * histo, const char * partName,  Float_t min = 0, Float_t max =3, Float_t scaleHisto = -1., Int_t fitFunc = kFitLevi, Int_t vartype = AliBWFunc::kdNdpt) {

  // Generic Macro to fit any particle using the PWG2/SPECTRA/Fit macros
  //
  // You have to provide:
  // - file: file name
  // - histo: histogram name name (assumend to be in the mail folder of the file)
  // - partName: it is used to get the mass of the particle from
  //   TDatabasePDG. If you are not sure, just use a part of the name: a
  //   list of names matching it is printed on screen
  //
  // You can optionally provide:
  // - min, max: the fit range
  // - scaleHisto: a scaling factor for the histo. If negative, it is
  //   ignored. If the histo is scaled, the bin width is also
  //   divided).
  // - fitFunc: id of the function, levi is the default
  // - varType: the variable used in the pt spectrum (see AliBWFunc.h)

  // load stuff
  gSystem->Load("libTree.so");
  gSystem->Load("libVMC.so");
  gSystem->Load("libMinuit.so");
  gSystem->Load("libSTEERBase.so");
  gSystem->Load("libESD.so");
  gSystem->Load("libAOD.so");
  gSystem->Load("libANALYSIS.so");
  gSystem->Load("libANALYSISalice.so");
  gSystem->Load("libCORRFW.so");
  gSystem->Load("libPWG2spectra.so");

  // get histo and draw
  AliBWFunc * fm = new AliBWFunc;
  fm->SetVarType(AliBWFunc::VarType_t(vartype));
  //  fm->SetVarType(AliBWFunc::VarType_t(0));//FIXME
  //  cout << "Warning: hacked vartype" << endl;

  if (!TDatabasePDG::Instance()->GetParticle(partName)) {
    cout << "Wrong particle name " << partName << endl;

    const THashList * l = TDatabasePDG::Instance()->ParticleList();
    Int_t npart = l->GetSize();
    for(Int_t ipart = 0; ipart < npart; ipart++){
      TString name = l->At(ipart)->GetName();
      if(name.Contains(partName, TString::kIgnoreCase))
	cout << " - Did you mean [" << name.Data() << "] ?" << endl;
    }

    cout << "Try [ TDatabasePDG::Instance()->GetParticle(partName) ] by hand "<< endl;
    return;

  }
  Double_t mass = TDatabasePDG::Instance()->GetParticle(partName)->Mass();
  TF1* func = 0;
  Int_t normPar = -1;
  if (fitFunc == kFitLevi)   {
    func = fm->GetLevi (mass, 0.2, 20,100);
    normPar = 0;
  }
  if (fitFunc == kFitExpPt)  {
    func = fm->GetPTExp(0.2, 20);
  }

  TFile * f = new TFile(file);
  TH1 * h = (TH1*) gDirectory->Get(histo); //
  h->Sumw2();
  if (scaleHisto > 0) h->Scale(scaleHisto, "width");
//   TH1 * h = AliBWTools::GetdNdPtFromOneOverPt((TH1*) gDirectory->Get(histo)); // FIXME
//   cout << "WARNING SCALING2PI" << endl;
//   h->Scale(2*TMath::Pi());//Fixme

//   h->Fit(func); // FIXME
//   gMinuit->Command("SET STRATEGY 2"); // FIXME

  if (!AliBWTools::Fit(h,func,min,max)) {
    cout << "Fitting error!" << endl;
    return;
  }

  TCanvas * c = new TCanvas();
  c->SetLogy();
  h->Draw();
  func->Draw("same");

  // Print results nicely
  AliLatexTable table(9,"c|ccccccc");
  table.InsertCustomRow("Part & Integral & T Slope & n & $\\Chi^2$/NDF & Min X & Frac Above & \\langle p_{t} \\rangle  & \\langle p_{t}^{2} \\rangle");
  // populate table
  Float_t yield  = func->Integral(0,100);
  Float_t yieldE = func->IntegralError(0,100);
//   Float_t yield  = func->Integral(0.45,1.05);
//   Float_t yieldE = func->IntegralError(0.45,1.05);
  Double_t tslope   = func->GetParameter(2);
  Double_t tslopeE = func->GetParError(2);

  table.SetNextCol(partName);
  table.SetNextCol(yield,yieldE,-4);
  table.SetNextCol(tslope,tslopeE,-4);
  table.SetNextCol(func->GetParameter(1),func->GetParError(1),-4);
  table.SetNextCol(Form("%2.2f/%d",func->GetChisquare(),func->GetNDF()));
  Float_t lowestPoint = TMath::Max(AliBWTools::GetLowestNotEmptyBinEdge(h),min);
  Float_t yieldAbove  = func->Integral(lowestPoint,100);
  table.SetNextCol(lowestPoint,-2);
  table.SetNextCol(yieldAbove/yield,-2);
  Float_t mean, meane;
  Float_t mean2, mean2e;
  AliBWTools::GetMean      (func, mean,  meane , 0.,100., normPar);
  AliBWTools::GetMeanSquare(func, mean2, mean2e, 0.,100., normPar);
  table.SetNextCol(mean,  meane ,-4);
  table.SetNextCol(mean2, mean2e,-4);
  //			 fMean2->IntegralError(0,100)/func->Integral(0,100),-7);
  table.InsertRow();
  table.PrintTable("ASCII");

}
<|endoftext|>


<commit_before>// Copyright 2010-2012 RethinkDB, all rights reserved.
#ifndef CLUSTERING_GENERIC_MULTI_THROTTLING_SERVER_HPP_
#define CLUSTERING_GENERIC_MULTI_THROTTLING_SERVER_HPP_

#include <algorithm>

#include "arch/timing.hpp"
#include "clustering/generic/multi_throttling_metadata.hpp"
#include "clustering/generic/registrar.hpp"
#include "rpc/mailbox/typed.hpp"

template <class request_type, class inner_client_business_card_type, class user_data_type, class registrant_type>
class multi_throttling_server_t :
        private repeating_timer_callback_t {
private:
    typedef typename multi_throttling_business_card_t<request_type, inner_client_business_card_type>::server_business_card_t server_business_card_t;
    typedef typename multi_throttling_business_card_t<request_type, inner_client_business_card_type>::client_business_card_t client_business_card_t;

public:
    multi_throttling_server_t(
            mailbox_manager_t *mm,
            user_data_type ud,
            int capacity) :
        mailbox_manager(mm),
        user_data(ud),
        total_tickets(capacity), free_tickets(capacity),
        reallocate_timer(reallocate_interval_ms, this),
        registrar(mailbox_manager, this)
        { }

    multi_throttling_business_card_t<request_type, inner_client_business_card_type> get_business_card() {
        return multi_throttling_business_card_t<request_type, inner_client_business_card_type>(
            registrar.get_business_card());
    }

private:
    static const int reallocate_interval_ms = 1000;

    class client_t :
            public intrusive_list_node_t<client_t>,
            private repeating_timer_callback_t {
    public:
        client_t(multi_throttling_server_t *p,
                const client_business_card_t &client_bc) :
            parent(p),
            target_tickets(0), held_tickets(0), in_use_tickets(0),

            time_of_last_qps_sample(get_ticks()),
            requests_since_last_qps_sample(0),
            running_qps_estimate(0),
            qps_sample_timer(reallocate_interval_ms, this),

            give_tickets_addr(client_bc.give_tickets_addr),
            reclaim_tickets_addr(client_bc.reclaim_tickets_addr),

            registrant(p->user_data, client_bc.inner_client_business_card),

            drainer(new auto_drainer_t),

            request_mailbox(new mailbox_t<void(request_type)>(parent->mailbox_manager,
                boost::bind(&client_t::on_request, this, _1),
                mailbox_callback_mode_inline)),
            relinquish_tickets_mailbox(new mailbox_t<void(int)>(parent->mailbox_manager,
                boost::bind(&client_t::on_relinquish_tickets, this, _1),
                mailbox_callback_mode_inline))
        {
            send(parent->mailbox_manager, client_bc.intro_addr,
                 server_business_card_t(request_mailbox->get_address(),
                                        relinquish_tickets_mailbox->get_address()));
            parent->clients.push_back(this);
            parent->recompute_allocations();
        }

        ~client_t() {
            parent->clients.remove(this);
            parent->recompute_allocations();
            request_mailbox.reset();
            relinquish_tickets_mailbox.reset();
            drainer.reset();
            guarantee(in_use_tickets == 0);
            parent->return_tickets(held_tickets);
        }

        void give_tickets(int tickets) {
            ASSERT_FINITE_CORO_WAITING;
            held_tickets += tickets;
            coro_t::spawn_sometime(boost::bind(
                &client_t::give_tickets_blocking, this,
                tickets,
                auto_drainer_t::lock_t(drainer.get())));
        }

        void set_target_tickets(int new_target) {
            if (target_tickets > new_target) {
                coro_t::spawn_sometime(boost::bind(
                    &client_t::reclaim_tickets_blocking, this,
                    target_tickets - new_target,
                    auto_drainer_t::lock_t(drainer.get())));
            }
            target_tickets = new_target;
        }

        int get_target_tickets() {
            return target_tickets;
        }

        int get_current_tickets() {
            return held_tickets + in_use_tickets;
        }

        int estimate_qps() {
            ticks_t time_span = get_ticks() - time_of_last_qps_sample;
            return running_qps_estimate / 2 +
                requests_since_last_qps_sample * secs_to_ticks(1) / time_span;
        }

    private:
        void on_request(const request_type &request) {
            guarantee(held_tickets > 0);
            held_tickets--;
            in_use_tickets++;
            coro_t::spawn_sometime(boost::bind(
                &client_t::perform_request, this,
                request,
                auto_drainer_t::lock_t(drainer.get())));
        }

        void perform_request(const request_type &request, auto_drainer_t::lock_t keepalive) {
            requests_since_last_qps_sample++;
            try {
                registrant.perform_request(request, keepalive.get_drain_signal());
            } catch (interrupted_exc_t) {
                /* ignore */
            }
            in_use_tickets--;
            parent->return_tickets(1);
        }

        void on_relinquish_tickets(int tickets) {
            held_tickets -= tickets;
            parent->return_tickets(tickets);
        }

        void give_tickets_blocking(int tickets, auto_drainer_t::lock_t) {
            send(parent->mailbox_manager, give_tickets_addr, tickets);
        }

        void reclaim_tickets_blocking(int tickets, auto_drainer_t::lock_t) {
            send(parent->mailbox_manager, reclaim_tickets_addr, tickets);
        }

        void on_ring() {
            /* Take a sample of the recent average QPS */
            running_qps_estimate = estimate_qps();
            time_of_last_qps_sample = get_ticks();
            requests_since_last_qps_sample = 0;
        }

        multi_throttling_server_t *parent;

        int target_tickets, held_tickets, in_use_tickets;

        ticks_t time_of_last_qps_sample;
        int requests_since_last_qps_sample;
        int running_qps_estimate;
        repeating_timer_t qps_sample_timer;

        mailbox_addr_t<void(int)> give_tickets_addr;
        mailbox_addr_t<void(int)> reclaim_tickets_addr;

        registrant_type registrant;

        scoped_ptr_t<auto_drainer_t> drainer;

        scoped_ptr_t<mailbox_t<void(request_type)> > request_mailbox;
        scoped_ptr_t<mailbox_t<void(int)> > relinquish_tickets_mailbox;
    };

    void on_ring() {
        recompute_allocations();
    }

    void recompute_allocations() {
        /* We divide the total number of tickets into two pools. The first pool
        is distributed evenly among all the clients. The second pool is
        distributed in proportion to the clients' QPS. */
        static const double fair_fraction = 0.1;
        int fair_tickets = static_cast<int>(total_tickets * fair_fraction);
        int qps_tickets = total_tickets - fair_tickets;
        int total_qps = 0;
        for (client_t *c = clients.head(); c; c = clients.next(c)) {
            total_qps += c->estimate_qps();
        }
        if (clients.size() == 0) {
            return;
        }
        if (total_qps == 0) {
            /* None of the clients did any queries recently. Not all of the
            tickets will be distributed, but that's OK. */
            total_qps = 1;
        }
        for (client_t *c = clients.head(); c; c = clients.next(c)) {
            /* This math isn't exact, but it's OK if the target tickets of all
            the clients don't add up to `total_tickets`. */
            c->set_target_tickets(fair_tickets / clients.size() +
                                  qps_tickets * c->estimate_qps() / total_qps);
        }
        redistribute_tickets();
    }

    void return_tickets(int tickets) {
        free_tickets += tickets;
        guarantee(free_tickets <= total_tickets);
        redistribute_tickets();
    }

    void redistribute_tickets() {
        static const int chunk_size = 100;
        static const int min_reasonable_tickets = 10;
        client_t *neediest;
        int gift_size;

        /* First, look for a client with a critically low number of tickets.
           They get priority in tickets. This prevents starvation. */
        while (free_tickets > 0) {
            gift_size = -1;
            neediest = NULL;
            for (client_t *c = clients.head(); c; c = clients.next(c)) {
                if (c->get_current_tickets() < min_reasonable_tickets && c->get_current_tickets() < c->get_target_tickets()) {
                    if (!neediest || c->get_current_tickets() < neediest->get_current_tickets()) {
                        neediest = c;
                        gift_size = std::min(c->get_target_tickets() - c->get_current_tickets(), free_tickets);
                    }
                }
            }

            if (!neediest) {
                break;
            }
            guarantee(gift_size >= 0);
            free_tickets -= gift_size;
            neediest->give_tickets(gift_size);
        }

        /* Next, look for clients with a large difference between their target
           number of tickets and their current number of tickets. But if the
           difference is less than `chunk_size`, don't send any tickets at all
           to avoid flooding the network with many small ticket updates. */
        while (free_tickets > chunk_size) {
            gift_size = -1;
            neediest = NULL;
            for (client_t *c = clients.head(); c; c = clients.next(c)) {
                int need_size = c->get_target_tickets() - c->get_current_tickets();
                if (need_size > chunk_size && (!neediest || need_size > neediest->get_target_tickets() - neediest->get_current_tickets())) {
                    neediest = c;
                    gift_size = chunk_size;
                }
            }

            if (!neediest) {
                break;
            }
            guarantee(gift_size >= 0);
            free_tickets -= gift_size;
            neediest->give_tickets(gift_size);
        }
    }

    mailbox_manager_t *const mailbox_manager;
    user_data_type user_data;

    intrusive_list_t<client_t> clients;
    int total_tickets, free_tickets;

    repeating_timer_t reallocate_timer;

    registrar_t<client_business_card_t, multi_throttling_server_t *, client_t> registrar;

private:
    DISABLE_COPYING(multi_throttling_server_t);
};

#endif /* CLUSTERING_GENERIC_MULTI_THROTTLING_SERVER_HPP_ */
<commit_msg>fixing potential divide-by-zero in multi_throttling_server<commit_after>// Copyright 2010-2012 RethinkDB, all rights reserved.
#ifndef CLUSTERING_GENERIC_MULTI_THROTTLING_SERVER_HPP_
#define CLUSTERING_GENERIC_MULTI_THROTTLING_SERVER_HPP_

#include <algorithm>

#include "arch/timing.hpp"
#include "clustering/generic/multi_throttling_metadata.hpp"
#include "clustering/generic/registrar.hpp"
#include "rpc/mailbox/typed.hpp"

template <class request_type, class inner_client_business_card_type, class user_data_type, class registrant_type>
class multi_throttling_server_t :
        private repeating_timer_callback_t {
private:
    typedef typename multi_throttling_business_card_t<request_type, inner_client_business_card_type>::server_business_card_t server_business_card_t;
    typedef typename multi_throttling_business_card_t<request_type, inner_client_business_card_type>::client_business_card_t client_business_card_t;

public:
    multi_throttling_server_t(
            mailbox_manager_t *mm,
            user_data_type ud,
            int capacity) :
        mailbox_manager(mm),
        user_data(ud),
        total_tickets(capacity), free_tickets(capacity),
        reallocate_timer(reallocate_interval_ms, this),
        registrar(mailbox_manager, this)
        { }

    multi_throttling_business_card_t<request_type, inner_client_business_card_type> get_business_card() {
        return multi_throttling_business_card_t<request_type, inner_client_business_card_type>(
            registrar.get_business_card());
    }

private:
    static const int reallocate_interval_ms = 1000;

    class client_t :
            public intrusive_list_node_t<client_t>,
            private repeating_timer_callback_t {
    public:
        client_t(multi_throttling_server_t *p,
                const client_business_card_t &client_bc) :
            parent(p),
            target_tickets(0), held_tickets(0), in_use_tickets(0),

            time_of_last_qps_sample(get_ticks()),
            requests_since_last_qps_sample(0),
            running_qps_estimate(0),
            qps_sample_timer(reallocate_interval_ms, this),

            give_tickets_addr(client_bc.give_tickets_addr),
            reclaim_tickets_addr(client_bc.reclaim_tickets_addr),

            registrant(p->user_data, client_bc.inner_client_business_card),

            drainer(new auto_drainer_t),

            request_mailbox(new mailbox_t<void(request_type)>(parent->mailbox_manager,
                boost::bind(&client_t::on_request, this, _1),
                mailbox_callback_mode_inline)),
            relinquish_tickets_mailbox(new mailbox_t<void(int)>(parent->mailbox_manager,
                boost::bind(&client_t::on_relinquish_tickets, this, _1),
                mailbox_callback_mode_inline))
        {
            send(parent->mailbox_manager, client_bc.intro_addr,
                 server_business_card_t(request_mailbox->get_address(),
                                        relinquish_tickets_mailbox->get_address()));
            parent->clients.push_back(this);
            parent->recompute_allocations();
        }

        ~client_t() {
            parent->clients.remove(this);
            parent->recompute_allocations();
            request_mailbox.reset();
            relinquish_tickets_mailbox.reset();
            drainer.reset();
            guarantee(in_use_tickets == 0);
            parent->return_tickets(held_tickets);
        }

        void give_tickets(int tickets) {
            ASSERT_FINITE_CORO_WAITING;
            held_tickets += tickets;
            coro_t::spawn_sometime(boost::bind(
                &client_t::give_tickets_blocking, this,
                tickets,
                auto_drainer_t::lock_t(drainer.get())));
        }

        void set_target_tickets(int new_target) {
            if (target_tickets > new_target) {
                coro_t::spawn_sometime(boost::bind(
                    &client_t::reclaim_tickets_blocking, this,
                    target_tickets - new_target,
                    auto_drainer_t::lock_t(drainer.get())));
            }
            target_tickets = new_target;
        }

        int get_target_tickets() {
            return target_tickets;
        }

        int get_current_tickets() {
            return held_tickets + in_use_tickets;
        }

        int estimate_qps() {
            ticks_t time_span = std::min<ticks_t>(get_ticks() - time_of_last_qps_sample, 1);
            return running_qps_estimate / 2 +
                requests_since_last_qps_sample * secs_to_ticks(1) / time_span;
        }

    private:
        void on_request(const request_type &request) {
            guarantee(held_tickets > 0);
            held_tickets--;
            in_use_tickets++;
            coro_t::spawn_sometime(boost::bind(
                &client_t::perform_request, this,
                request,
                auto_drainer_t::lock_t(drainer.get())));
        }

        void perform_request(const request_type &request, auto_drainer_t::lock_t keepalive) {
            requests_since_last_qps_sample++;
            try {
                registrant.perform_request(request, keepalive.get_drain_signal());
            } catch (interrupted_exc_t) {
                /* ignore */
            }
            in_use_tickets--;
            parent->return_tickets(1);
        }

        void on_relinquish_tickets(int tickets) {
            held_tickets -= tickets;
            parent->return_tickets(tickets);
        }

        void give_tickets_blocking(int tickets, auto_drainer_t::lock_t) {
            send(parent->mailbox_manager, give_tickets_addr, tickets);
        }

        void reclaim_tickets_blocking(int tickets, auto_drainer_t::lock_t) {
            send(parent->mailbox_manager, reclaim_tickets_addr, tickets);
        }

        void on_ring() {
            /* Take a sample of the recent average QPS */
            running_qps_estimate = estimate_qps();
            time_of_last_qps_sample = get_ticks();
            requests_since_last_qps_sample = 0;
        }

        multi_throttling_server_t *parent;

        int target_tickets, held_tickets, in_use_tickets;

        ticks_t time_of_last_qps_sample;
        int requests_since_last_qps_sample;
        int running_qps_estimate;
        repeating_timer_t qps_sample_timer;

        mailbox_addr_t<void(int)> give_tickets_addr;
        mailbox_addr_t<void(int)> reclaim_tickets_addr;

        registrant_type registrant;

        scoped_ptr_t<auto_drainer_t> drainer;

        scoped_ptr_t<mailbox_t<void(request_type)> > request_mailbox;
        scoped_ptr_t<mailbox_t<void(int)> > relinquish_tickets_mailbox;
    };

    void on_ring() {
        recompute_allocations();
    }

    void recompute_allocations() {
        /* We divide the total number of tickets into two pools. The first pool
        is distributed evenly among all the clients. The second pool is
        distributed in proportion to the clients' QPS. */
        static const double fair_fraction = 0.1;
        int fair_tickets = static_cast<int>(total_tickets * fair_fraction);
        int qps_tickets = total_tickets - fair_tickets;
        int total_qps = 0;
        for (client_t *c = clients.head(); c; c = clients.next(c)) {
            total_qps += c->estimate_qps();
        }
        if (clients.size() == 0) {
            return;
        }
        if (total_qps == 0) {
            /* None of the clients did any queries recently. Not all of the
            tickets will be distributed, but that's OK. */
            total_qps = 1;
        }
        for (client_t *c = clients.head(); c; c = clients.next(c)) {
            /* This math isn't exact, but it's OK if the target tickets of all
            the clients don't add up to `total_tickets`. */
            c->set_target_tickets(fair_tickets / clients.size() +
                                  qps_tickets * c->estimate_qps() / total_qps);
        }
        redistribute_tickets();
    }

    void return_tickets(int tickets) {
        free_tickets += tickets;
        guarantee(free_tickets <= total_tickets);
        redistribute_tickets();
    }

    void redistribute_tickets() {
        static const int chunk_size = 100;
        static const int min_reasonable_tickets = 10;
        client_t *neediest;
        int gift_size;

        /* First, look for a client with a critically low number of tickets.
           They get priority in tickets. This prevents starvation. */
        while (free_tickets > 0) {
            gift_size = -1;
            neediest = NULL;
            for (client_t *c = clients.head(); c; c = clients.next(c)) {
                if (c->get_current_tickets() < min_reasonable_tickets && c->get_current_tickets() < c->get_target_tickets()) {
                    if (!neediest || c->get_current_tickets() < neediest->get_current_tickets()) {
                        neediest = c;
                        gift_size = std::min(c->get_target_tickets() - c->get_current_tickets(), free_tickets);
                    }
                }
            }

            if (!neediest) {
                break;
            }
            guarantee(gift_size >= 0);
            free_tickets -= gift_size;
            neediest->give_tickets(gift_size);
        }

        /* Next, look for clients with a large difference between their target
           number of tickets and their current number of tickets. But if the
           difference is less than `chunk_size`, don't send any tickets at all
           to avoid flooding the network with many small ticket updates. */
        while (free_tickets > chunk_size) {
            gift_size = -1;
            neediest = NULL;
            for (client_t *c = clients.head(); c; c = clients.next(c)) {
                int need_size = c->get_target_tickets() - c->get_current_tickets();
                if (need_size > chunk_size && (!neediest || need_size > neediest->get_target_tickets() - neediest->get_current_tickets())) {
                    neediest = c;
                    gift_size = chunk_size;
                }
            }

            if (!neediest) {
                break;
            }
            guarantee(gift_size >= 0);
            free_tickets -= gift_size;
            neediest->give_tickets(gift_size);
        }
    }

    mailbox_manager_t *const mailbox_manager;
    user_data_type user_data;

    intrusive_list_t<client_t> clients;
    int total_tickets, free_tickets;

    repeating_timer_t reallocate_timer;

    registrar_t<client_business_card_t, multi_throttling_server_t *, client_t> registrar;

private:
    DISABLE_COPYING(multi_throttling_server_t);
};

#endif /* CLUSTERING_GENERIC_MULTI_THROTTLING_SERVER_HPP_ */
<|endoftext|>


<commit_before>/*
* C S O U N D   V S T
*
* A VST plugin version of Csound, with Python scripting.
*
* L I C E N S E
*
* This software 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 software 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 software; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/
#ifndef EXCEPTION_H
#define EXCEPTION_H
#include "Platform.hpp"
#ifdef SWIG
%module CsoundAC
%{
#include <string>
%}
#else
#include <string>
#endif

namespace csound
{
        /**
        * Base class for C++ exceptions in the Silence system.
        */
        class SILENCE_PUBLIC Exception
        {
                std::string message;
        public:
                Exception(std::string message);
                virtual ~Exception();
                std::string getMessage() const;
        };
}

#endif
<commit_msg>Adding missing definitions.<commit_after>/*
 * C S O U N D   V S T
 *
 * A VST plugin version of Csound, with Python scripting.
 *
 * L I C E N S E
 *
 * This software 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 software 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 software; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
#ifndef EXCEPTION_H
#define EXCEPTION_H
#include "Platform.hpp"
#ifdef SWIG
%module CsoundAC
%{
#include <string>
  %}
#else
#include <string>
#endif

namespace csound
{
  /**
   * Base class for C++ exceptions in the Silence system.
   */
  class SILENCE_PUBLIC Exception
  {
    std::string message;
  public:
    Exception(std::string message_) :
      message(message_)
      {
      }
    virtual ~Exception()
    {
    }
    std::string getMessage() const
    {
      return message;
    }
  };
}

#endif
<|endoftext|>