<commit_before>/* bcnn include */
#include <bcnn/bcnn.h>
#include <bcnn/bcnn_cl.h>
#include <bh/bh.h>
#include <bh/bh_error.h>
#include <bh/bh_string.h>

/* tflite generated flatbuffers */
#include "schema_generated.h"

void load_mnist_model(bcnn_net* net, const char* model_path) {
    bcnn_net_set_input_shape(net, 28, 28, 1, 16);
    bcnn_add_convolutional_layer(net, 32, 3, 1, 1, 0, XAVIER, RELU, 0, "input",
                                 "conv1");
    bcnn_add_batchnorm_layer(net, "conv1", "bn1");
    bcnn_add_maxpool_layer(net, 2, 2, "bn1", "pool1");
    bcnn_add_convolutional_layer(net, 32, 3, 1, 1, 0, XAVIER, RELU, 0, "pool1",
                                 "conv2");
    bcnn_add_batchnorm_layer(net, "conv2", "bn2");
    bcnn_add_maxpool_layer(net, 2, 2, "bn2", "pool2");
    bcnn_add_fullc_layer(net, 256, XAVIER, RELU, 0, "pool2", "fc1");
    bcnn_add_batchnorm_layer(net, "fc1", "bn3");
    bcnn_add_fullc_layer(net, 10, XAVIER, RELU, 0, "bn3", "fc2");
    bcnn_add_softmax_layer(net, "fc2", "softmax");
    bcnn_load_model(net, model_path);
}

flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<tflite::Tensor>>>
export_tensors(bcnn_net* net, FlatBufferBuilder* builder,
               std::vector<const bcnn_tensor*>* buffers_to_write) {
    std::vector<flatbuffers::Offset<tflite::Tensor>> tensor_vector;
    tensor_vector.reserve(net->num_tensors);
    for (int i = 0; i < net->num_tensors; ++i) {
        int buffer_index = buffers_to_write->size();
        buffers_to_write->push_back(&net->tensors[i]);
        // shape: [batch size, height, width, number of channels] (That's
        // Tensorflow's NHWC)
        std::vector<int> shape = {net->tensors[i].n, net->tensors[i].c,
                                  net->tensors[i].h, net->tensors[i].w};
        tensor_vector[i] = tflite::CreateTensorDirect(
            *builder, &shape, tflite::TensorType_FLOAT32, buffer_index,
            net->tensors[i].name,
            /*quantization=*/0);
    }
    return builder->CreateVector(tensor_vector);
}

flatbuffers::Offset<flatbuffers::Vector<int32_t>> export_input_tensors(
    bcnn_net* net, FlatBufferBuilder* builder) {
    std::vector<int32_t> inputs;
    // Currently, bcnn is limited to one input
    inputs.push_back(0);
    return builder->CreateVector<int32_t>(inputs);
}

flatbuffers::Offset<flatbuffers::Vector<int32_t>> export_output_tensors(
    bcnn_net* net, FlatBufferBuilder* builder) {
    std::vector<int32_t> outputs;
    // Super hacky
    outputs.push_back(net->tensors[net->num_tensors - 1]);
    return builder->CreateVector<int32_t>(outputs);
}

static const std::map<bcnn_layer_type, tflite::BuiltinOperator>
    bcnn_tflite_ops_map = {{CONVOLUTIONAL, BuiltinOperator_CONV_2D},
                           {DECONVOLUTIONAL, BuiltinOperator_TRANSPOSE_CONV},
                           {DEPTHWISE_CONV, BuiltinOperator_DEPTHWISE_CONV_2D},
                           {FULL_CONNECTED, BuiltinOperator_FULLY_CONNECTED},
                           {MAXPOOL, BuiltinOperator_MAX_POOL_2D},
                           {AVGPOOL, BuiltinOperator_AVERAGE_POOL_2D},
                           {SOFTMAX, BuiltinOperator_SOFTMAX},
                           {CONCAT, BuiltinOperator_CONCATENATION}};

static const std::map<bcnn_activation, BuiltinOperator> bcnn_tflite_act_map = {
    {RELU, BuiltinOperator_RELU},
    {LOGISTIC, BuiltinOperator_LOGISTIC},
    {PRELU, BuiltinOperator_PRELU}};

flatbuffers::Offset<
    flatbuffers::Vector<flatbuffers::Offset<tflite::OperatorCode>>>
export_operator_codes(
    bcnn_net* net,
    const std::map<bcnn_layer_type, BuiltinOperator>& bcnn_tflite_ops_map,
    const std::map<bcnn_activation, BuiltinOperator>& bcnn_tflite_act_map,
    const FlatBufferBuilder* builder) {
    /*std::map<bcnn_layer_type, BuiltinOperator> bcnn_tflite_ops_map;
    std::map<bcnn_activation, BuiltinOperator> bcnn_tflite_act_map;
    bcnn_tflite_ops_map[CONVOLUTIONAL] = BuiltinOperator_CONV_2D;
    bcnn_tflite_ops_map[DECONVOLUTIONAL] = BuiltinOperator_TRANSPOSE_CONV;
    bcnn_tflite_ops_map[DEPTHWISE_CONV] = BuiltinOperator_DEPTHWISE_CONV_2D;
    bcnn_tflite_ops_map[FULL_CONNECTED] = BuiltinOperator_FULLY_CONNECTED;
    bcnn_tflite_ops_map[MAXPOOL] = BuiltinOperator_MAX_POOL_2D;
    bcnn_tflite_ops_map[AVGPOOL] = BuiltinOperator_AVERAGE_POOL_2D;
    bcnn_tflite_ops_map[SOFTMAX] = BuiltinOperator_SOFTMAX;
    bcnn_tflite_ops_map[CONCAT] = BuiltinOperator_CONCATENATION;
    bcnn_tflite_act_map[RELU] = BuiltinOperator_RELU;
    bcnn_tflite_act_map[LOGISTIC] = BuiltinOperator_LOGISTIC;
    bcnn_tflite_act_map[PRELU] = BuiltinOperator_PRELU;*/

    std::vector<flatbuffers::Offset<tflite::OperatorCode>> opcode_vector;
    opcode_vector.reserve(net->num_nodes);
    for (int i = 0; i < net->num_nodes; ++i) {
        if (net->nodes[i].layer->type != ACTIVATION) {
            if (bcnn_tflite_ops_map.count(net->nodes[i].layer->type) > 0) {
                opcode_vector[i] = tflite::CreateOperatorCode(
                    *builder, bcnn_tflite_ops_map[net->nodes[i].layer->type], 0,
                    /*op_version=*/1);
            } else {
                fprintf(stderr, "[ERROR] The operator %d is not supported",
                        net->nodes[i].layer->type);
                return nullptr;
            }
        } else {
            if (bcnn_tflite_act_map.count(net->nodes[i].layer->type) > 0) {
                opcode_vector[i] = tflite::CreateOperatorCode(
                    *builder, bcnn_tflite_ops_map[net->nodes[i].layer->type], 0,
                    /*op_version=*/1);
            } else {
                fprintf(stderr, "[ERROR] The activation %d is not supported",
                        net->nodes[i].layer->type);
                return nullptr;
            }
        }
    }
    return builder->CreateVector(opcode_vector);
}

flatbuffers::Offset<Vector<flatbuffers::Offset<tflite::Operator>>>
export_operators(
    bcnn_net* net,
    const std::map<bcnn_layer_type, BuiltinOperator>& bcnn_tflite_ops_map,
    const std::map<bcnn_activation, BuiltinOperator>& bcnn_tflite_act_map,
    const std::map<OperatorType, std::unique_ptr<BaseOperator>>& ops_by_type,
    const details::OperatorsMap& operators_map,
    const details::TensorsMap& tensors_map, FlatBufferBuilder* builder) {
    std::vector<flatbuffers::Offset<tflite::Operator>> op_vector;
    for (int i = 0; i < net->num_nodes; ++i) {
        std::vector<int32_t> inputs;
        for (int j = 0; j < net->nodes[i].num_src; ++j) {
            inputs.push_back(net->tensors[net->nodes[i].src[j]]);
        }
        std::vector<int32_t> outputs;
        for (int j = 0; j < net->nodes[i].num_dst; ++j) {
            outputs.push_back(net->tensors[net->nodes[i].dst[j]]);
        }
    }

    for (const auto& op : model.operators) {
        std::vector<int32_t> inputs;
        for (const string& input : op->inputs) {
            // -1 is the ID for optional tensor in TFLite output
            int id = model.IsOptionalArray(input) ? -1 : tensors_map.at(input);
            inputs.push_back(id);
        }
        std::vector<int32_t> outputs;
        for (const string& output : op->outputs) {
            outputs.push_back(tensors_map.at(output));
        }

        int op_index = operators_map.at(GetOperatorKey(*op, ops_by_type));

        // This is a custom op unless we can find it in ops_by_type, and even
        // then
        // it could be a custom op (such as kTensorFlowUnsupported).

        auto options = Options::Custom(0);
        if (ops_by_type.count(op->type) != 0) {
            options = ops_by_type.at(op->type)->Serialize(*op, builder);
        }
        // The only supported CustomOptionFormat is FLEXBUFFERS now.
        op_vector.push_back(CreateOperator(
            *builder, op_index, builder->CreateVector(inputs),
            builder->CreateVector(outputs), options.type, options.builtin,
            options.custom, ::tflite::CustomOptionsFormat_FLEXBUFFERS));
    }

    return builder->CreateVector(op_vector);
}

void convert_bcnn_to_flatbuffers_tflite(bcnn_net* net,
                                        const char* out_tflite_path) {
    flatbuffers::FlatBufferBuilder builder(/*initial_size=*/10240);

    // Export tensors
    std::vector<const bcnn_tensor*> buffers_to_write;
    bcnn_tensor empty_array;
    buffers_to_write.push_back(&bcnn_tensor);

    // Finish builder
    // TODO Finish(); ...
    const uint8_t* buffer = builder.GetBufferPointer();
    int size = builder.GetSize();
    // Save to file
    FILE* f_tflite = NULL;
    f_tflite = fopen(out_tflite_path, "wb");
    fwrite(buffer, sizeof(uint8_t), size, f_tflite);
    fclose(f_tflite);
}

int main(int argc, char** argv) {
    if (argc < 4) {
        fprintf(stderr, "Usage: %s <in.bcnnconf> <in.bcnnmodel> <out.tflite>\n",
                argv[0]);
        return -1;
    }

    bcnn_net* net = NULL;
    bcnn_init_net(&net);

    load_mnist_model(net, argv[2]);

    bcnn_end_net(&net);

    return 0;
}<commit_msg>Add tflite converter (WIP)<commit_after>/* bcnn include */
#include <bcnn/bcnn.h>
#include <bcnn/bcnn_cl.h>
#include <bh/bh.h>
#include <bh/bh_error.h>
#include <bh/bh_string.h>

/* tflite generated flatbuffers */
#include "schema_generated.h"

void load_mnist_model(bcnn_net* net, const char* model_path) {
    bcnn_net_set_input_shape(net, 28, 28, 1, 16);
    bcnn_add_convolutional_layer(net, 32, 3, 1, 1, 0, XAVIER, RELU, 0, "input",
                                 "conv1");
    bcnn_add_batchnorm_layer(net, "conv1", "bn1");
    bcnn_add_maxpool_layer(net, 2, 2, "bn1", "pool1");
    bcnn_add_convolutional_layer(net, 32, 3, 1, 1, 0, XAVIER, RELU, 0, "pool1",
                                 "conv2");
    bcnn_add_batchnorm_layer(net, "conv2", "bn2");
    bcnn_add_maxpool_layer(net, 2, 2, "bn2", "pool2");
    bcnn_add_fullc_layer(net, 256, XAVIER, RELU, 0, "pool2", "fc1");
    bcnn_add_batchnorm_layer(net, "fc1", "bn3");
    bcnn_add_fullc_layer(net, 10, XAVIER, RELU, 0, "bn3", "fc2");
    bcnn_add_softmax_layer(net, "fc2", "softmax");
    bcnn_load_model(net, model_path);
}

flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<tflite::Tensor>>>
export_tensors(bcnn_net* net, FlatBufferBuilder* builder,
               std::vector<const bcnn_tensor*>* buffers_to_write) {
    std::vector<flatbuffers::Offset<tflite::Tensor>> tensor_vector;
    tensor_vector.reserve(net->num_tensors);
    for (int i = 0; i < net->num_tensors; ++i) {
        int buffer_index = buffers_to_write->size();
        buffers_to_write->push_back(&net->tensors[i]);
        // shape: [batch size, height, width, number of channels] (That's
        // Tensorflow's NHWC)
        std::vector<int> shape = {net->tensors[i].n, net->tensors[i].c,
                                  net->tensors[i].h, net->tensors[i].w};
        tensor_vector[i] = tflite::CreateTensorDirect(
            *builder, &shape, tflite::TensorType_FLOAT32, buffer_index,
            net->tensors[i].name,
            /*quantization=*/0);
    }
    return builder->CreateVector(tensor_vector);
}

flatbuffers::Offset<flatbuffers::Vector<int32_t>> export_input_tensors(
    bcnn_net* net, FlatBufferBuilder* builder) {
    std::vector<int32_t> inputs;
    // Currently, bcnn is limited to one input
    inputs.push_back(0);
    return builder->CreateVector<int32_t>(inputs);
}

flatbuffers::Offset<flatbuffers::Vector<int32_t>> export_output_tensors(
    bcnn_net* net, FlatBufferBuilder* builder) {
    std::vector<int32_t> outputs;
    // Super hacky
    outputs.push_back(net->tensors[net->num_tensors - 1]);
    return builder->CreateVector<int32_t>(outputs);
}

static const std::map<bcnn_layer_type, tflite::BuiltinOperator>
    bcnn_tflite_ops_map = {{CONVOLUTIONAL, BuiltinOperator_CONV_2D},
                           {DECONVOLUTIONAL, BuiltinOperator_TRANSPOSE_CONV},
                           {DEPTHWISE_CONV, BuiltinOperator_DEPTHWISE_CONV_2D},
                           {FULL_CONNECTED, BuiltinOperator_FULLY_CONNECTED},
                           {MAXPOOL, BuiltinOperator_MAX_POOL_2D},
                           {AVGPOOL, BuiltinOperator_AVERAGE_POOL_2D},
                           {SOFTMAX, BuiltinOperator_SOFTMAX},
                           {CONCAT, BuiltinOperator_CONCATENATION}};

static const std::map<bcnn_activation, BuiltinOperator> bcnn_tflite_act_map = {
    {RELU, BuiltinOperator_RELU},
    {LOGISTIC, BuiltinOperator_LOGISTIC},
    {PRELU, BuiltinOperator_PRELU}};

flatbuffers::Offset<
    flatbuffers::Vector<flatbuffers::Offset<tflite::OperatorCode>>>
export_operator_codes(
    bcnn_net* net,
    const std::map<bcnn_layer_type, BuiltinOperator>& bcnn_tflite_ops_map,
    const std::map<bcnn_activation, BuiltinOperator>& bcnn_tflite_act_map,
    const FlatBufferBuilder* builder) {
    /*std::map<bcnn_layer_type, BuiltinOperator> bcnn_tflite_ops_map;
    std::map<bcnn_activation, BuiltinOperator> bcnn_tflite_act_map;
    bcnn_tflite_ops_map[CONVOLUTIONAL] = BuiltinOperator_CONV_2D;
    bcnn_tflite_ops_map[DECONVOLUTIONAL] = BuiltinOperator_TRANSPOSE_CONV;
    bcnn_tflite_ops_map[DEPTHWISE_CONV] = BuiltinOperator_DEPTHWISE_CONV_2D;
    bcnn_tflite_ops_map[FULL_CONNECTED] = BuiltinOperator_FULLY_CONNECTED;
    bcnn_tflite_ops_map[MAXPOOL] = BuiltinOperator_MAX_POOL_2D;
    bcnn_tflite_ops_map[AVGPOOL] = BuiltinOperator_AVERAGE_POOL_2D;
    bcnn_tflite_ops_map[SOFTMAX] = BuiltinOperator_SOFTMAX;
    bcnn_tflite_ops_map[CONCAT] = BuiltinOperator_CONCATENATION;
    bcnn_tflite_act_map[RELU] = BuiltinOperator_RELU;
    bcnn_tflite_act_map[LOGISTIC] = BuiltinOperator_LOGISTIC;
    bcnn_tflite_act_map[PRELU] = BuiltinOperator_PRELU;*/

    std::vector<flatbuffers::Offset<tflite::OperatorCode>> opcode_vector;
    opcode_vector.reserve(net->num_nodes);
    for (int i = 0; i < net->num_nodes; ++i) {
        if (net->nodes[i].layer->type != ACTIVATION) {
            if (bcnn_tflite_ops_map.count(net->nodes[i].layer->type) > 0) {
                opcode_vector[i] = tflite::CreateOperatorCode(
                    *builder, bcnn_tflite_ops_map[net->nodes[i].layer->type], 0,
                    /*op_version=*/1);
            } else {
                fprintf(stderr, "[ERROR] The operator %d is not supported",
                        net->nodes[i].layer->type);
                return nullptr;
            }
        } else {
            if (bcnn_tflite_act_map.count(net->nodes[i].layer->type) > 0) {
                opcode_vector[i] = tflite::CreateOperatorCode(
                    *builder, bcnn_tflite_ops_map[net->nodes[i].layer->type], 0,
                    /*op_version=*/1);
            } else {
                fprintf(stderr, "[ERROR] The activation %d is not supported",
                        net->nodes[i].layer->type);
                return nullptr;
            }
        }
    }
    return builder->CreateVector(opcode_vector);
}

flatbuffers::Offset<Vector<flatbuffers::Offset<tflite::Operator>>>
export_operators(
    bcnn_net* net,
    const std::map<bcnn_layer_type, BuiltinOperator>& bcnn_tflite_ops_map,
    const std::map<bcnn_activation, BuiltinOperator>& bcnn_tflite_act_map,
    const std::map<OperatorType, std::unique_ptr<BaseOperator>>& ops_by_type,
    const details::OperatorsMap& operators_map,
    const details::TensorsMap& tensors_map, FlatBufferBuilder* builder) {
    std::vector<flatbuffers::Offset<tflite::Operator>> op_vector;
    for (int i = 0; i < net->num_nodes; ++i) {
        // We need to check manually for each type of layer, the inputs /
        // outputs
        std::vector<int32_t> inputs;
        for (int j = 0; j < net->nodes[i].num_src; ++j) {
            inputs.push_back(net->tensors[net->nodes[i].src[j]]);
        }
        std::vector<int32_t> outputs;
        for (int j = 0; j < net->nodes[i].num_dst; ++j) {
            outputs.push_back(net->tensors[net->nodes[i].dst[j]]);
        }
    }
    // TODO WIP....
    for (const auto& op : model.operators) {
        std::vector<int32_t> inputs;
        for (const string& input : op->inputs) {
            // -1 is the ID for optional tensor in TFLite output
            int id = model.IsOptionalArray(input) ? -1 : tensors_map.at(input);
            inputs.push_back(id);
        }
        std::vector<int32_t> outputs;
        for (const string& output : op->outputs) {
            outputs.push_back(tensors_map.at(output));
        }

        int op_index = operators_map.at(GetOperatorKey(*op, ops_by_type));

        // This is a custom op unless we can find it in ops_by_type, and even
        // then
        // it could be a custom op (such as kTensorFlowUnsupported).

        auto options = Options::Custom(0);
        if (ops_by_type.count(op->type) != 0) {
            options = ops_by_type.at(op->type)->Serialize(*op, builder);
        }
        // The only supported CustomOptionFormat is FLEXBUFFERS now.
        op_vector.push_back(CreateOperator(
            *builder, op_index, builder->CreateVector(inputs),
            builder->CreateVector(outputs), options.type, options.builtin,
            options.custom, ::tflite::CustomOptionsFormat_FLEXBUFFERS));
    }

    return builder->CreateVector(op_vector);
}

void convert_bcnn_to_flatbuffers_tflite(bcnn_net* net,
                                        const char* out_tflite_path) {
    flatbuffers::FlatBufferBuilder builder(/*initial_size=*/10240);

    // Export tensors
    std::vector<const bcnn_tensor*> buffers_to_write;
    bcnn_tensor empty_array;
    buffers_to_write.push_back(&bcnn_tensor);

    // Finish builder
    // TODO Finish(); ...
    const uint8_t* buffer = builder.GetBufferPointer();
    int size = builder.GetSize();
    // Save to file
    FILE* f_tflite = NULL;
    f_tflite = fopen(out_tflite_path, "wb");
    fwrite(buffer, sizeof(uint8_t), size, f_tflite);
    fclose(f_tflite);
}

int main(int argc, char** argv) {
    if (argc < 4) {
        fprintf(stderr, "Usage: %s <in.bcnnconf> <in.bcnnmodel> <out.tflite>\n",
                argv[0]);
        return -1;
    }

    bcnn_net* net = NULL;
    bcnn_init_net(&net);

    load_mnist_model(net, argv[2]);

    bcnn_end_net(&net);

    return 0;
}<|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS writercorehandoff (1.4.326); FILE MERGED 2005/09/13 16:30:22 tra 1.4.326.3: RESYNC: (1.4-1.5); FILE MERGED 2005/06/07 14:15:28 fme 1.4.326.2: #i50348# General cleanup - removed unused header files, functions, members, declarations etc. 2005/06/06 09:29:25 tra 1.4.326.1: Unnecessary includes removed #i50348#<commit_after><|endoftext|>


<commit_before><commit_msg>Initial SwEditWin::LogicMouseButtonDown/Up<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Ignacio Avas
 * For the full copyright and license information, please view the LICENSE.txt
 * file that was distributed with this source code.
*/

#include "ILP.h"
#include "logging/Logger.h"
#include "util/sutil.h"
#include "conditions/Condition.h"
#include "conditions/ConditionPosition.h"
#include "optimizations/OptimizationFunction.h"
#include "optimizations/Evaluation.h"
#include "Configuration.h"
#include <ctime>

ILP::ILP():
	scene(NULL),
	optimizationFunction(NULL),
	currentIteration(0),
	logger(NULL),
	renderer(NULL),
	inited(false)
{
}

#include "optimizations/SurfaceRadiosityEvaluation.h"
static void reevalCandidate(Logger *logger, OptimizationFunction *optimizationFunction, Evaluation *candidateObj)
{
	static const int tries = 400;

	auto candidate = (SurfaceRadiosityEvaluation *)candidateObj;
	float mid = 0;
	float M2 = 0;
	auto evals = std::vector<SurfaceRadiosityEvaluation *>(tries);

	for(int i = 1; i <= tries; ++i){
		auto candidateReeval = (SurfaceRadiosityEvaluation *)(optimizationFunction->evaluateFast());
		evals[i-1] = candidateReeval;

		float x = candidateReeval->val();
		float delta = x - mid;
		mid += delta / i;
		M2 += delta * (x - mid);
	}

	int inRange = 0;
	for(auto eval: evals)
	{
		if(fabs(eval->val() - mid) <= eval->radius())
			++inRange;
	}

	float diff = sqrtf(M2 / tries-1);

	logger->log("%8.2f\t%8.2f\t%8.2f\t%8.2f\t%0.2f\t%0.2f\n", candidate->val(), mid, candidate->radius(), diff, inRange/(float)tries, diff * 1.96f);
}

static int getRetriesForRadius(float radius)
{
	int res = ceilf(sqrtf(radius) * 200.0f);
	return res;
}

static float getShuffleRadius(float progress)
{
	return 0.5f * (0.5f + sinf(2.0f * (float)M_PI * progress - 0.5f * (float)M_PI) / 2.0f);
}

void ILP::optimize()
{
	if(!inited){
		throw std::logic_error("ILP is not inited");
	}

	qsrand(time(NULL));

	// first solution
	QVector<Configuration> bestConfigurations;
	bestConfigurations.append(processInitialConfiguration());

	double start = sutilCurrentTime();

	// apply ILP
	while(currentIteration < maxIterations)
	{
		float radius = 0.05f;
		while(radius < 1.0f){
			float suffleRadius = getShuffleRadius((float) currentIteration / maxIterations);
			bool improvementFound = findFirstImprovement(bestConfigurations, radius,  suffleRadius, getRetriesForRadius(radius));
			if(improvementFound){
				radius = 0.05f;
			} else {
				radius += 0.05;
			}
		}
		logger->log("Done navigating whole neighbourhood: %d\n", currentIteration);
	}
	double totalTime = sutilCurrentTime() - start;

	logger->log("%d iterations on %0.2fs. %0.2fs per iteration\n",
		(currentIteration+1), totalTime, totalTime/(currentIteration+1));

	logBestConfigurations(bestConfigurations);
}

Configuration ILP::processInitialConfiguration()
{
	logIterationHeader();
	auto initialEval = optimizationFunction->evaluateFast();
	auto initialPositions = QVector<ConditionPosition *>();
	for(auto conditionIt = conditions.begin(); conditionIt != conditions.end(); ++conditionIt){
		initialPositions.append((*conditionIt)->initial());
	}
	auto initialConfig = Configuration(initialEval, initialPositions);
	logger->log("Initial solution: %s\n", initialEval->infoShort().toStdString().c_str() );
	logIterationResults(initialConfig.positions(), initialEval);
	++currentIteration;
	return initialConfig;
}

static bool appendAndRemoveWorse(QVector<Configuration> &currentEvals, Evaluation *candidate, QVector<ConditionPosition *> &positions)
{
	QVector<Configuration> evals = currentEvals;
	currentEvals.clear();

	bool candidateIsGoodEnough = false;
	for(auto i = 0; i < evals.size(); ++i){
		auto comp = candidate->compare(evals.at(i).evaluation());
		if(comp != EvaluationResult::BETTER){
			currentEvals.append(evals.at(i));
		}

		if(!candidateIsGoodEnough && comp != EvaluationResult::WORSE){
			candidateIsGoodEnough = true;
			currentEvals.append(Configuration(candidate, positions));
		}
	}
	return candidateIsGoodEnough;
}

bool ILP::findFirstImprovement(QVector<Configuration> &configurations, float maxRadius, float shuffleRadius, int retries)
{
	static const int neighbourhoodRetries = 20;

	while(retries-- > 0){
		// move the reference point to some element of the configuration file
		int someConfigIdx = rand() % configurations.length();
		auto positions = configurations.at(someConfigIdx).positions();

		// shuffle condition positions a bit
		int shuffled;
		for(shuffled = 0; shuffled < positions.size(); ++shuffled){
			auto currentShuffleRadius = shuffleRadius * qrand() / RAND_MAX;
			auto neighbour = conditions.at(shuffled)->findNeighbour(positions.at(shuffled), currentShuffleRadius, retries);
			if(!neighbour){
				break; // can't shuffle
			}
			positions[shuffled] = neighbour;
		}
		if(shuffled < positions.size()){
			continue; // can't shuffle
		}

		// find neighbours
		auto neighbourPosition = findAllNeighbours(positions, neighbourhoodRetries, maxRadius);
		if(neighbourPosition.empty()){
			continue; // no neighbours
		}

		// evaluate function
		for(auto it = neighbourPosition.begin(); it != neighbourPosition.end(); ++it){
			(*it)->apply(renderer);
		}
		auto candidate = optimizationFunction->evaluateFast();
		logIterationResults(positions, candidate);
		reevalCandidate(logger, optimizationFunction, candidate);
		++currentIteration;

		// crop worse solutions
		bool isGoodEnough = appendAndRemoveWorse(configurations, candidate, neighbourPosition);

		// evaluate if the solution is an improvement
		if(isGoodEnough && configurations.length() == 1){
			logger->log("Better solution: %s\n", candidate->infoShort().toStdString().c_str());
			return true;
		} else {
			if(!isGoodEnough) {
				// removes candidate and positions from memory
				delete candidate;
				for(auto it = neighbourPosition.begin(); it != neighbourPosition.end(); ++it){
					delete *it;
				}
			} else {
				logger->log("Probable solution: %s\n", candidate->infoShort().toStdString().c_str());
			}
		}
	}
	return false;
}

QVector<ConditionPosition *> ILP::findAllNeighbours(QVector<ConditionPosition *> &currentPositions, int optimizationsRetries,  float maxRadius)
{
	QVector<ConditionPosition *> res;

	float radius = maxRadius * qrand() / RAND_MAX;

	// generate partitions
	auto corradius = QVector<float>() << 0.0f;
	for(int i = 0; i < conditions.size()-1; ++i){
		corradius.append(radius * qrand() / RAND_MAX);
	}
	corradius << radius;
	qSort(corradius);

	for(int i = 0; i < conditions.size(); ++i){
		auto neighbourRadius = corradius.at(i+1) - corradius.at(i);
		auto neighbour = conditions.at(i)->findNeighbour(currentPositions.at(i), neighbourRadius, optimizationsRetries);
		if(neighbour == NULL){
			for(auto it = res.begin(); it != res.end(); ++it){
				delete *it;
			}
			res.clear();
			return res; // empty array: no neighbours
		} else {
			res.append(neighbour);
		}
	}
	return res;
}

QString ILP::getImageFileName()
{
	return  outputDir.filePath(
		QString("evaluation-%1.png").arg(currentIteration, 4, 10, QLatin1Char('0'))
	);
}

QString ILP::getImageFileNameSolution(int solutionNum)
{
	return  outputDir.filePath(
		QString("evaluation-solution-%1.png").arg(solutionNum, 4, 10, QLatin1Char('0'))
	);
}
<commit_msg>Remove old reevalCandidate() function from ILP<commit_after>/*
 * Copyright (c) 2014 Ignacio Avas
 * For the full copyright and license information, please view the LICENSE.txt
 * file that was distributed with this source code.
*/

#include "ILP.h"
#include "logging/Logger.h"
#include "util/sutil.h"
#include "conditions/Condition.h"
#include "conditions/ConditionPosition.h"
#include "optimizations/OptimizationFunction.h"
#include "optimizations/Evaluation.h"
#include "Configuration.h"
#include <ctime>

ILP::ILP():
	scene(NULL),
	optimizationFunction(NULL),
	currentIteration(0),
	logger(NULL),
	renderer(NULL),
	inited(false)
{
}

static int getRetriesForRadius(float radius)
{
	int res = ceilf(sqrtf(radius) * 200.0f);
	return res;
}

static float getShuffleRadius(float progress)
{
	return 0.5f * (0.5f + sinf(2.0f * (float)M_PI * progress - 0.5f * (float)M_PI) / 2.0f);
}

void ILP::optimize()
{
	if(!inited){
		throw std::logic_error("ILP is not inited");
	}

	qsrand(time(NULL));

	// first solution
	QVector<Configuration> bestConfigurations;
	bestConfigurations.append(processInitialConfiguration());

	double start = sutilCurrentTime();

	// apply ILP
	while(currentIteration < maxIterations)
	{
		float radius = 0.05f;
		while(radius < 1.0f){
			float suffleRadius = getShuffleRadius((float) currentIteration / maxIterations);
			bool improvementFound = findFirstImprovement(bestConfigurations, radius,  suffleRadius, getRetriesForRadius(radius));
			if(improvementFound){
				radius = 0.05f;
			} else {
				radius += 0.05;
			}
		}
		logger->log("Done navigating whole neighbourhood: %d\n", currentIteration);
	}
	double totalTime = sutilCurrentTime() - start;

	logger->log("%d iterations on %0.2fs. %0.2fs per iteration\n",
		(currentIteration+1), totalTime, totalTime/(currentIteration+1));

	logBestConfigurations(bestConfigurations);
}

Configuration ILP::processInitialConfiguration()
{
	logIterationHeader();
	auto initialEval = optimizationFunction->evaluateFast();
	auto initialPositions = QVector<ConditionPosition *>();
	for(auto conditionIt = conditions.begin(); conditionIt != conditions.end(); ++conditionIt){
		initialPositions.append((*conditionIt)->initial());
	}
	auto initialConfig = Configuration(initialEval, initialPositions);
	logger->log("Initial solution: %s\n", initialEval->infoShort().toStdString().c_str() );
	logIterationResults(initialConfig.positions(), initialEval);
	++currentIteration;
	return initialConfig;
}

static bool appendAndRemoveWorse(QVector<Configuration> &currentEvals, Evaluation *candidate, QVector<ConditionPosition *> &positions)
{
	QVector<Configuration> evals = currentEvals;
	currentEvals.clear();

	bool candidateIsGoodEnough = false;
	for(auto i = 0; i < evals.size(); ++i){
		auto comp = candidate->compare(evals.at(i).evaluation());
		if(comp != EvaluationResult::BETTER){
			currentEvals.append(evals.at(i));
		}

		if(!candidateIsGoodEnough && comp != EvaluationResult::WORSE){
			candidateIsGoodEnough = true;
			currentEvals.append(Configuration(candidate, positions));
		}
	}
	return candidateIsGoodEnough;
}

bool ILP::findFirstImprovement(QVector<Configuration> &configurations, float maxRadius, float shuffleRadius, int retries)
{
	static const int neighbourhoodRetries = 20;

	while(retries-- > 0){
		// move the reference point to some element of the configuration file
		int someConfigIdx = rand() % configurations.length();
		auto positions = configurations.at(someConfigIdx).positions();

		// shuffle condition positions a bit
		int shuffled;
		for(shuffled = 0; shuffled < positions.size(); ++shuffled){
			auto currentShuffleRadius = shuffleRadius * qrand() / RAND_MAX;
			auto neighbour = conditions.at(shuffled)->findNeighbour(positions.at(shuffled), currentShuffleRadius, retries);
			if(!neighbour){
				break; // can't shuffle
			}
			positions[shuffled] = neighbour;
		}
		if(shuffled < positions.size()){
			continue; // can't shuffle
		}

		// find neighbours
		auto neighbourPosition = findAllNeighbours(positions, neighbourhoodRetries, maxRadius);
		if(neighbourPosition.empty()){
			continue; // no neighbours
		}

		// evaluate function
		for(auto it = neighbourPosition.begin(); it != neighbourPosition.end(); ++it){
			(*it)->apply(renderer);
		}
		auto candidate = optimizationFunction->evaluateFast();
		logIterationResults(positions, candidate);
		++currentIteration;

		// crop worse solutions
		bool isGoodEnough = appendAndRemoveWorse(configurations, candidate, neighbourPosition);

		// evaluate if the solution is an improvement
		if(isGoodEnough && configurations.length() == 1){
			logger->log("Better solution: %s\n", candidate->infoShort().toStdString().c_str());
			return true;
		} else {
			if(!isGoodEnough) {
				// removes candidate and positions from memory
				delete candidate;
				for(auto it = neighbourPosition.begin(); it != neighbourPosition.end(); ++it){
					delete *it;
				}
			} else {
				logger->log("Probable solution: %s\n", candidate->infoShort().toStdString().c_str());
			}
		}
	}
	return false;
}

QVector<ConditionPosition *> ILP::findAllNeighbours(QVector<ConditionPosition *> &currentPositions, int optimizationsRetries,  float maxRadius)
{
	QVector<ConditionPosition *> res;

	float radius = maxRadius * qrand() / RAND_MAX;

	// generate partitions
	auto corradius = QVector<float>() << 0.0f;
	for(int i = 0; i < conditions.size()-1; ++i){
		corradius.append(radius * qrand() / RAND_MAX);
	}
	corradius << radius;
	qSort(corradius);

	for(int i = 0; i < conditions.size(); ++i){
		auto neighbourRadius = corradius.at(i+1) - corradius.at(i);
		auto neighbour = conditions.at(i)->findNeighbour(currentPositions.at(i), neighbourRadius, optimizationsRetries);
		if(neighbour == NULL){
			for(auto it = res.begin(); it != res.end(); ++it){
				delete *it;
			}
			res.clear();
			return res; // empty array: no neighbours
		} else {
			res.append(neighbour);
		}
	}
	return res;
}

QString ILP::getImageFileName()
{
	return  outputDir.filePath(
		QString("evaluation-%1.png").arg(currentIteration, 4, 10, QLatin1Char('0'))
	);
}

QString ILP::getImageFileNameSolution(int solutionNum)
{
	return  outputDir.filePath(
		QString("evaluation-solution-%1.png").arg(solutionNum, 4, 10, QLatin1Char('0'))
	);
}
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

#include <TString.h>
#include <TRandom.h>

#include "AliITSresponseSDD.h"

//___________________________________________
ClassImp(AliITSresponseSDD)

AliITSresponseSDD::AliITSresponseSDD()
{
  // constructor
  //   fModules = 520;
  //   fChips = 4;
  //   fChannels = 64;
   SetDeadChannels();
   SetMaxAdc();
   SetDiffCoeff();
   SetDriftSpeed();
   SetNSigmaIntegration();
   SetNLookUp();
   // SetClock();
   SetNoiseParam();
   SetNoiseAfterElectronics();
   SetElectronics();
   SetDynamicRange();
   SetChargeLoss();
   SetMinVal();
   SetParamOptions();
   SetZeroSupp();
   SetDataType();
   SetFilenames();
   SetOutputOption();
   SetDo10to8();
   // set the default zero suppression parameters
   fCPar[0]=0;
   fCPar[1]=0;
   fCPar[2]=(Int_t)(fBaseline + 2.*fNoiseAfterEl + 0.2);
   fCPar[3]=(Int_t)(fBaseline + 2.*fNoiseAfterEl + 0.2);
   fCPar[4]=0;
   fCPar[5]=0;
   fCPar[6]=0;
   fCPar[7]=0;
}

AliITSresponseSDD::~AliITSresponseSDD() {

  if(fGaus) delete fGaus;

}

void AliITSresponseSDD::SetCompressParam(Int_t  cp[8])
{
  // set compression param

    Int_t i;
    for (i=0; i<8; i++) {
	fCPar[i]=cp[i];
	//printf("\n CompressPar %d %d \n",i,fCPar[i]);

    }
}
void AliITSresponseSDD::GiveCompressParam(Int_t  cp[8])
{
  // give compression param

    Int_t i;
    for (i=0; i<8; i++) {
	cp[i]=fCPar[i];
    }
}

void AliITSresponseSDD::SetDeadChannels(Int_t nmod, Int_t nchip, Int_t nchan) {

  for(Int_t m=0; m<fModules; m++)
    for(Int_t n=0; n<fChips; n++)
      for(Int_t p=0; p<fChannels; p++)
	fGain[m][n][p] = 1.;

  if(nmod < 0 || nmod > fModules) { cout << "Wrong number of dead modules: " << nmod << endl; return; }
  Int_t nmax = (fModules-nmod)*fChips;
  if(nchip < 0 || nchip > nmax) { cout << "Wrong number of dead chips: " << nchip << endl; return; }
  nmax = ((fModules - nmod)*fChips - nchip)*fChannels;
  if(nchan < 0 || nchan > nmax) { cout << "Wrong number of dead channels: " << nchan << endl; return; }

  TRandom *gran = new TRandom();

//  cout << "modules" << endl;
  Int_t mod[nmod];
  for(Int_t i=0;i<nmod;i++) {
    mod[i] = (Int_t) (1.+fModules*gran->Uniform());
    cout << i+1 << ": Dead module nr: " << mod[i] << endl;
    for(Int_t n=0; n<fChips; n++)
      for(Int_t p=0; p<fChannels; p++)
	fGain[mod[i]-1][n][p] = 0.;
  }

//  cout << "chips" << endl;
  Int_t chip[nchip];
  Int_t chip_mod[nchip];
  Int_t i=0;
  while(i<nchip) {
    Int_t module = (Int_t) (fModules*gran->Uniform() + 1.);
    if(module <=0 || module > fModules) cout << "Wrong module: " << module << endl;
    Int_t flag_mod = 0;
    for(Int_t k=0;k<nmod;k++) if(module == mod[k]) flag_mod = 1;
    if(flag_mod == 1) continue;
    Int_t chi = (Int_t) (fChips*gran->Uniform() + 1.);
    if(chi <=0 || chi > fChips) cout << "Wrong chip: " << chi << endl;
    i++;
    chip[i-1] = chi;
    chip_mod[i-1] = module;
    for(Int_t m=0; m<fChannels; m++) fGain[module-1][chi-1][m] = 0.;
    cout << i << ": Dead chip nr. " << chip[i-1] << " in module nr: " << chip_mod[i-1] << endl;
  }

//  cout << "channels" << endl;
  Int_t channel[nchan];
  Int_t channel_chip[nchan];
  Int_t channel_mod[nchan];
  i=0;
  while(i<nchan) {
    Int_t module = (Int_t) (fModules*gran->Uniform() + 1.);
    if(module <=0 || module > fModules) cout << "Wrong module: " << module << endl;
    Int_t flag_mod = 0;
    for(Int_t k=0;k<nmod;k++) if(module == mod[k]) flag_mod = 1;
    if(flag_mod == 1) continue;
    Int_t chipp = (Int_t) (fChips*gran->Uniform() + 1.);
    if(chipp <=0 || chipp > fChips) cout << "Wrong chip: " << chipp << endl;
    Int_t flag_chip = 0;
    for(Int_t k=0;k<nchip;k++) if(chipp == chip[k] && module == chip_mod[k]) flag_chip = 1;
    if(flag_chip == 1) continue;
    i++;
    channel[i-1] = (Int_t) (fChannels*gran->Uniform() + 1.);
    if(channel[i-1] <=0 || channel[i-1] > fChannels) cout << "Wrong channel: " << channel[i-1] << endl;
    channel_chip[i-1] = chipp;
    channel_mod[i-1] = module;
    fGain[module-1][chipp-1][channel[i-1]-1] = 0.;
    cout << i << ": Dead channel nr. " << channel[i-1] << " in chip nr. " << channel_chip[i-1] << " in module nr: " << channel_mod[i-1] << endl;
  }

  /*
  delete [] mod;
  delete [] chip;
  delete [] chip_mod;
  delete [] channel;
  delete [] channel_mod;
  delete [] channel_chip;
  */
}

void AliITSresponseSDD::PrintGains()
{
  // Print SDD electronic gains
  for(Int_t t=0; t<fModules;t++)
    for(Int_t u=0; u<fChips;u++)
      for(Int_t v=0; v<fChannels;v++)
	cout << "Gain for Module: " << t+1 << ", Chip " << u+1 << ", Channel " << v+1 << " = " << fGain[t][u][v] << endl;

}

void AliITSresponseSDD::Print()
{
  // Print SDD response Parameters

   cout << "**************************************************" << endl;
   cout << "   Silicon Drift Detector Response Parameters    " << endl;
   cout << "**************************************************" << endl;
   cout << "Diffusion Coefficients: " << fDiffCoeff << ", " << fDiffCoeff1 << endl;

   cout << "Hardware compression parameters: " << endl;
   for(Int_t i=0; i<8; i++) cout << "fCPar[" << i << "] = " << fCPar[i] << endl;
   cout << "Noise before electronics (arbitrary units): " << fNoise << endl;
   cout << "Baseline (ADC units): " << fBaseline << endl;
   cout << "Noise after electronics (ADC units): " << fNoiseAfterEl << endl;

   cout << "Dynamic Range: " << fDynamicRange << endl;
   cout << "Charge Loss: " << fChargeLoss << endl;
   cout << "Temperature: " << fTemperature << endl;
   cout << "Drift Speed: " << fDriftSpeed << endl;
   cout << "Electronics (1=PASCAL, 2=OLA): " << fElectronics << endl;

   cout << "N. of Sigma for signal integration: " << fNsigmas << endl;
   cout << "N. of bins in lookup table: " << fNcomps << endl;

   cout << "Max. ADC Value: " << fMaxAdc << endl;
   cout << "Min. Value: " << fMinVal << endl;

   cout << "**************************************************" << endl;
   cout << "             Print Electronics Gains              " << endl;
   cout << "**************************************************" << endl;
   PrintGains();

}

<commit_msg>Arrays with variable length declared using oparetor new<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

#include <TString.h>
#include <TRandom.h>

#include "AliITSresponseSDD.h"

//___________________________________________
ClassImp(AliITSresponseSDD)

AliITSresponseSDD::AliITSresponseSDD()
{
  // constructor
  //   fModules = 520;
  //   fChips = 4;
  //   fChannels = 64;
   SetDeadChannels();
   SetMaxAdc();
   SetDiffCoeff();
   SetDriftSpeed();
   SetNSigmaIntegration();
   SetNLookUp();
   // SetClock();
   SetNoiseParam();
   SetNoiseAfterElectronics();
   SetElectronics();
   SetDynamicRange();
   SetChargeLoss();
   SetMinVal();
   SetParamOptions();
   SetZeroSupp();
   SetDataType();
   SetFilenames();
   SetOutputOption();
   SetDo10to8();
   // set the default zero suppression parameters
   fCPar[0]=0;
   fCPar[1]=0;
   fCPar[2]=(Int_t)(fBaseline + 2.*fNoiseAfterEl + 0.2);
   fCPar[3]=(Int_t)(fBaseline + 2.*fNoiseAfterEl + 0.2);
   fCPar[4]=0;
   fCPar[5]=0;
   fCPar[6]=0;
   fCPar[7]=0;
}

AliITSresponseSDD::~AliITSresponseSDD() {

  if(fGaus) delete fGaus;

}

void AliITSresponseSDD::SetCompressParam(Int_t  cp[8])
{
  // set compression param

    Int_t i;
    for (i=0; i<8; i++) {
	fCPar[i]=cp[i];
	//printf("\n CompressPar %d %d \n",i,fCPar[i]);

    }
}
void AliITSresponseSDD::GiveCompressParam(Int_t  cp[8])
{
  // give compression param

    Int_t i;
    for (i=0; i<8; i++) {
	cp[i]=fCPar[i];
    }
}

void AliITSresponseSDD::SetDeadChannels(Int_t nmod, Int_t nchip, Int_t nchan) {

  for(Int_t m=0; m<fModules; m++)
    for(Int_t n=0; n<fChips; n++)
      for(Int_t p=0; p<fChannels; p++)
	fGain[m][n][p] = 1.;

  if(nmod < 0 || nmod > fModules) { cout << "Wrong number of dead modules: " << nmod << endl; return; }
  Int_t nmax = (fModules-nmod)*fChips;
  if(nchip < 0 || nchip > nmax) { cout << "Wrong number of dead chips: " << nchip << endl; return; }
  nmax = ((fModules - nmod)*fChips - nchip)*fChannels;
  if(nchan < 0 || nchan > nmax) { cout << "Wrong number of dead channels: " << nchan << endl; return; }

  TRandom *gran = new TRandom();

//  cout << "modules" << endl;
  Int_t * mod = new Int_t [nmod];
  for(Int_t i=0;i<nmod;i++) {
    mod[i] = (Int_t) (1.+fModules*gran->Uniform());
    cout << i+1 << ": Dead module nr: " << mod[i] << endl;
    for(Int_t n=0; n<fChips; n++)
      for(Int_t p=0; p<fChannels; p++)
	fGain[mod[i]-1][n][p] = 0.;
  }

//  cout << "chips" << endl;
  Int_t * chip = new Int_t[nchip];
  Int_t * chip_mod = new Int_t[nchip];
  Int_t i=0;
  while(i<nchip) {
    Int_t module = (Int_t) (fModules*gran->Uniform() + 1.);
    if(module <=0 || module > fModules) cout << "Wrong module: " << module << endl;
    Int_t flag_mod = 0;
    for(Int_t k=0;k<nmod;k++) if(module == mod[k]) flag_mod = 1;
    if(flag_mod == 1) continue;
    Int_t chi = (Int_t) (fChips*gran->Uniform() + 1.);
    if(chi <=0 || chi > fChips) cout << "Wrong chip: " << chi << endl;
    i++;
    chip[i-1] = chi;
    chip_mod[i-1] = module;
    for(Int_t m=0; m<fChannels; m++) fGain[module-1][chi-1][m] = 0.;
    cout << i << ": Dead chip nr. " << chip[i-1] << " in module nr: " << chip_mod[i-1] << endl;
  }

//  cout << "channels" << endl;
  Int_t * channel = new Int_t[nchan];
  Int_t * channel_chip = new Int_t[nchan];
  Int_t * channel_mod = new Int_t[nchan];
  i=0;
  while(i<nchan) {
    Int_t module = (Int_t) (fModules*gran->Uniform() + 1.);
    if(module <=0 || module > fModules) cout << "Wrong module: " << module << endl;
    Int_t flag_mod = 0;
    for(Int_t k=0;k<nmod;k++) if(module == mod[k]) flag_mod = 1;
    if(flag_mod == 1) continue;
    Int_t chipp = (Int_t) (fChips*gran->Uniform() + 1.);
    if(chipp <=0 || chipp > fChips) cout << "Wrong chip: " << chipp << endl;
    Int_t flag_chip = 0;
    for(Int_t k=0;k<nchip;k++) if(chipp == chip[k] && module == chip_mod[k]) flag_chip = 1;
    if(flag_chip == 1) continue;
    i++;
    channel[i-1] = (Int_t) (fChannels*gran->Uniform() + 1.);
    if(channel[i-1] <=0 || channel[i-1] > fChannels) cout << "Wrong channel: " << channel[i-1] << endl;
    channel_chip[i-1] = chipp;
    channel_mod[i-1] = module;
    fGain[module-1][chipp-1][channel[i-1]-1] = 0.;
    cout << i << ": Dead channel nr. " << channel[i-1] << " in chip nr. " << channel_chip[i-1] << " in module nr: " << channel_mod[i-1] << endl;
  }

  delete [] mod;
  delete [] chip;
  delete [] chip_mod;
  delete [] channel;
  delete [] channel_mod;
  delete [] channel_chip;
}

void AliITSresponseSDD::PrintGains()
{
  // Print SDD electronic gains
  for(Int_t t=0; t<fModules;t++)
    for(Int_t u=0; u<fChips;u++)
      for(Int_t v=0; v<fChannels;v++)
	cout << "Gain for Module: " << t+1 << ", Chip " << u+1 << ", Channel " << v+1 << " = " << fGain[t][u][v] << endl;

}

void AliITSresponseSDD::Print()
{
  // Print SDD response Parameters

   cout << "**************************************************" << endl;
   cout << "   Silicon Drift Detector Response Parameters    " << endl;
   cout << "**************************************************" << endl;
   cout << "Diffusion Coefficients: " << fDiffCoeff << ", " << fDiffCoeff1 << endl;

   cout << "Hardware compression parameters: " << endl;
   for(Int_t i=0; i<8; i++) cout << "fCPar[" << i << "] = " << fCPar[i] << endl;
   cout << "Noise before electronics (arbitrary units): " << fNoise << endl;
   cout << "Baseline (ADC units): " << fBaseline << endl;
   cout << "Noise after electronics (ADC units): " << fNoiseAfterEl << endl;

   cout << "Dynamic Range: " << fDynamicRange << endl;
   cout << "Charge Loss: " << fChargeLoss << endl;
   cout << "Temperature: " << fTemperature << endl;
   cout << "Drift Speed: " << fDriftSpeed << endl;
   cout << "Electronics (1=PASCAL, 2=OLA): " << fElectronics << endl;

   cout << "N. of Sigma for signal integration: " << fNsigmas << endl;
   cout << "N. of bins in lookup table: " << fNcomps << endl;

   cout << "Max. ADC Value: " << fMaxAdc << endl;
   cout << "Min. Value: " << fMinVal << endl;

   cout << "**************************************************" << endl;
   cout << "             Print Electronics Gains              " << endl;
   cout << "**************************************************" << endl;
   PrintGains();

}

<|endoftext|>


<commit_before>#include "CLSmith/CLProgramGenerator.h"

#include <cassert>
#include <cmath>
#include <memory>
#include <string>
#include <iostream>

#include "CLSmith/CLExpression.h"
#include "CLSmith/CLOptions.h"
#include "CLSmith/CLVariable.h"
#include "CLSmith/Divergence.h"
#include "CLSmith/ExpressionAtomic.h"
#include "ExpressionID.h"
#include "CLSmith/FunctionInvocationBuiltIn.h"
#include "CLSmith/StatementAtomicResult.h"
#include "CLSmith/Globals.h"
#include "CLSmith/StatementAtomicReduction.h"
#include "CLSmith/StatementBarrier.h"
#include "CLSmith/StatementComm.h"
#include "CLSmith/StatementEMI.h"
#include "CLSmith/StatementMessage.h"
#include "CLSmith/Vector.h"
#include "Function.h"
#include "Type.h"

class OutputMgr;

namespace CLSmith {
namespace {
static const unsigned int max_threads = 10000;
static const unsigned int max_thr_per_dim = 100;
static const unsigned int max_threads_per_group = 256;
static const unsigned int no_dims = 3;
static unsigned int noThreads = 1;
static unsigned int noGroups = 1;
static std::vector<unsigned int> *globalDim;
static std::vector<unsigned int> *localDim;
}  // namespace

void CLProgramGenerator::goGenerator() {
  // Initialise probabilies.
  CLExpression::InitProbabilityTable();
  CLStatement::InitProbabilityTable();
  // Create vector types.
  Vector::GenerateVectorTypes();
  // Initialise function tables.
  FunctionInvocationBuiltIn::InitTables();
  // Initialise Variable objects used for thread identifiers.
  ExpressionID::Initialise();
  // Initialize runtime parameters;
  InitRuntimeParameters();
  // Initalize atomic parameters
  if (CLOptions::atomics())
    ExpressionAtomic::InitAtomics();
  // Initialise buffers used for inter-thread communication.
  StatementComm::InitBuffers();
  // Initialise Message Passing data.
  MessagePassing::Initialise();

  // Expects argc, argv and seed. These vars should really be in the output_mgr.
  output_mgr_->OutputHeader(0, NULL, seed_);

  // This creates the random program, the rest handles post-processing and
  // outputting the program.
  GenerateAllTypes();
  GenerateFunctions();

  // If tracking divergence is set, perform the tracking now.
  std::unique_ptr<Divergence> div;
  if (CLOptions::track_divergence()) {
    div.reset(new Divergence());
    div->ProcessEntryFunction(GetFirstFunction());
  }

  // If EMI block generation is set, prune them.
  if (CLOptions::emi())
    EMIController::GetEMIController()->PruneEMISections();

  // If atomic blocks are generated, add operations for the special values
  if (CLOptions::atomics())
    StatementAtomicResult::GenSpecialVals();

  // If atomic reductions are generated, add the hash buffer
  if (CLOptions::atomic_reductions())
    StatementAtomicReduction::RecordBuffer();

  // If Message Passing is enabled, create orderings and message updates.
  if (CLOptions::message_passing())
    MessagePassing::CreateMessageOrderings();

  // At this point, all the global variables that have been created throughout
  // program generation should have been created. Any global variables added to
  // VariableSelector's global list after this point must be added to globals
  // manually, or the name will not be prepended with the global struct.
  Globals *globals = Globals::GetGlobals();

  // Once the global struct is created, we add the global memory buffers.
  // Adding global memory buffers to do with atomic expressions.
  if (CLOptions::atomics()) {
    ExpressionAtomic::AddVarsToGlobals(globals);
  }

  // Add the reduction variables for atomic reductions to the global struct
  if (CLOptions::atomic_reductions())
    StatementAtomicReduction::AddVarsToGlobals(globals);

  // Now add the input data for EMI sections if specified.
  if (CLOptions::emi())
    for (MemoryBuffer *mb :
        *EMIController::GetEMIController()->GetItemisedEMIInput())
      globals->AddGlobalMemoryBuffer(mb);

  // Add the 9 variables used for the identifiers.
  if (CLOptions::fake_divergence())
    ExpressionID::AddVarsToGlobals(globals);

  // Add buffers used for inter-thread comm.
  if (CLOptions::inter_thread_comm())
    StatementComm::AddVarsToGlobals(globals);

  // Add messages for message passing.
  if (CLOptions::message_passing())
    MessagePassing::AddMessageVarsToGlobals(globals);

  // If barriers have been set, use the divergence information to place them.
  if (CLOptions::barriers()) {
    if (CLOptions::divergence()) GenerateBarriers(div.get(), globals);
    else { /*TODO Non-div barriers*/ }
  }

  if (CLOptions::small())
    CLSmith::CLVariable::ParseUnusedVars();

  // Output the whole program.
  output_mgr_->Output();

  // Release any singleton instances used.
  Globals::ReleaseGlobals();
  EMIController::ReleaseEMIController();
}

void CLProgramGenerator::InitRuntimeParameters() {
  globalDim = new std::vector<unsigned int>(no_dims, 1);
  localDim = new std::vector<unsigned int>(no_dims, 1);
  std::vector<unsigned int>& globalDim = *CLSmith::globalDim;
  std::vector<unsigned int>& localDim = *CLSmith::localDim;
  std::vector<unsigned int> chosen_div;
  std::vector<unsigned int> divisors;
  for (unsigned int i = 0; i < no_dims; i++) {
    globalDim[i] = rnd_upto(std::min(max_thr_per_dim, max_threads / noThreads));
    noThreads *= globalDim[i];
  }
  unsigned int curr_thr_p_grp;
  do {
    curr_thr_p_grp = 1;
    for (unsigned int i = 0; i < no_dims; i++) {
      get_divisors(globalDim[i], &divisors);
      localDim[i] = divisors[rnd_upto(divisors.size())];
      curr_thr_p_grp *= localDim[i];
    }
  } while (curr_thr_p_grp > max_threads_per_group);
  for (unsigned int i = 0; i < no_dims; i++)
    noGroups *= globalDim[i] / localDim[i];
}

OutputMgr *CLProgramGenerator::getOutputMgr() {
  return output_mgr_.get();
}

std::string CLProgramGenerator::get_count_prefix(const std::string& name) {
  assert(false);
  return "";
}

const unsigned int CLProgramGenerator::get_threads() {
  return noThreads;
}

const unsigned int CLProgramGenerator::get_groups() {
  return noGroups;
}

const unsigned int CLProgramGenerator::get_total_threads() {
  return noThreads * noGroups;
}

const unsigned int CLProgramGenerator::get_threads_per_group() {
  return noThreads / noGroups;
}

const std::vector<unsigned int>& CLProgramGenerator::get_global_dims() {
  return *globalDim;
}

const std::vector<unsigned int>& CLProgramGenerator::get_local_dims() {
  return *localDim;
}

const unsigned int CLProgramGenerator::get_atomic_blocks_no() {
  return CLSmith::ExpressionAtomic::get_atomic_blocks_no();
}

void CLProgramGenerator::initialize() {
}

void CLProgramGenerator::get_divisors(
    unsigned int val, std::vector<unsigned int> *divisors) {
  divisors->clear();
  divisors->push_back(1); divisors->push_back(val);
  unsigned int i;
  for (i = 2; i < sqrt(val); i++) {
    if (!(val % i)) {
      divisors->push_back(i);
      divisors->push_back(val / i);
    }
  }
  if (i * i == val)
    divisors->push_back(i);
}

}  // namespace CLSmith
<commit_msg>Fixed a bug with the previous change, spotted by Pflanzer Moritz.<commit_after>#include "CLSmith/CLProgramGenerator.h"

#include <cassert>
#include <cmath>
#include <memory>
#include <string>
#include <iostream>

#include "CLSmith/CLExpression.h"
#include "CLSmith/CLOptions.h"
#include "CLSmith/CLVariable.h"
#include "CLSmith/Divergence.h"
#include "CLSmith/ExpressionAtomic.h"
#include "ExpressionID.h"
#include "CLSmith/FunctionInvocationBuiltIn.h"
#include "CLSmith/StatementAtomicResult.h"
#include "CLSmith/Globals.h"
#include "CLSmith/StatementAtomicReduction.h"
#include "CLSmith/StatementBarrier.h"
#include "CLSmith/StatementComm.h"
#include "CLSmith/StatementEMI.h"
#include "CLSmith/StatementMessage.h"
#include "CLSmith/Vector.h"
#include "Function.h"
#include "Type.h"

class OutputMgr;

namespace CLSmith {
namespace {
static const unsigned int max_threads = 10000;
static const unsigned int max_thr_per_dim = 100;
static const unsigned int max_threads_per_group = 256;
static const unsigned int no_dims = 3;
static unsigned int noThreads = 1;
static unsigned int noGroups = 1;
static std::vector<unsigned int> *globalDim;
static std::vector<unsigned int> *localDim;
}  // namespace

void CLProgramGenerator::goGenerator() {
  // Initialise probabilies.
  CLExpression::InitProbabilityTable();
  CLStatement::InitProbabilityTable();
  // Create vector types.
  Vector::GenerateVectorTypes();
  // Initialise function tables.
  FunctionInvocationBuiltIn::InitTables();
  // Initialise Variable objects used for thread identifiers.
  ExpressionID::Initialise();
  // Initialize runtime parameters;
  InitRuntimeParameters();
  // Initalize atomic parameters
  if (CLOptions::atomics())
    ExpressionAtomic::InitAtomics();
  // Initialise buffers used for inter-thread communication.
  StatementComm::InitBuffers();
  // Initialise Message Passing data.
  MessagePassing::Initialise();

  // Expects argc, argv and seed. These vars should really be in the output_mgr.
  output_mgr_->OutputHeader(0, NULL, seed_);

  // This creates the random program, the rest handles post-processing and
  // outputting the program.
  GenerateAllTypes();
  GenerateFunctions();

  // If tracking divergence is set, perform the tracking now.
  std::unique_ptr<Divergence> div;
  if (CLOptions::track_divergence()) {
    div.reset(new Divergence());
    div->ProcessEntryFunction(GetFirstFunction());
  }

  // If EMI block generation is set, prune them.
  if (CLOptions::emi())
    EMIController::GetEMIController()->PruneEMISections();

  // If atomic blocks are generated, add operations for the special values
  if (CLOptions::atomics())
    StatementAtomicResult::GenSpecialVals();

  // If atomic reductions are generated, add the hash buffer
  if (CLOptions::atomic_reductions())
    StatementAtomicReduction::RecordBuffer();

  // If Message Passing is enabled, create orderings and message updates.
  if (CLOptions::message_passing())
    MessagePassing::CreateMessageOrderings();

  // At this point, all the global variables that have been created throughout
  // program generation should have been created. Any global variables added to
  // VariableSelector's global list after this point must be added to globals
  // manually, or the name will not be prepended with the global struct.
  Globals *globals = Globals::GetGlobals();

  // Once the global struct is created, we add the global memory buffers.
  // Adding global memory buffers to do with atomic expressions.
  if (CLOptions::atomics()) {
    ExpressionAtomic::AddVarsToGlobals(globals);
  }

  // Add the reduction variables for atomic reductions to the global struct
  if (CLOptions::atomic_reductions())
    StatementAtomicReduction::AddVarsToGlobals(globals);

  // Now add the input data for EMI sections if specified.
  if (CLOptions::emi())
    for (MemoryBuffer *mb :
        *EMIController::GetEMIController()->GetItemisedEMIInput())
      globals->AddGlobalMemoryBuffer(mb);

  // Add the 9 variables used for the identifiers.
  if (CLOptions::fake_divergence())
    ExpressionID::AddVarsToGlobals(globals);

  // Add buffers used for inter-thread comm.
  if (CLOptions::inter_thread_comm())
    StatementComm::AddVarsToGlobals(globals);

  // Add messages for message passing.
  if (CLOptions::message_passing())
    MessagePassing::AddMessageVarsToGlobals(globals);

  // If barriers have been set, use the divergence information to place them.
  if (CLOptions::barriers()) {
    if (CLOptions::divergence()) GenerateBarriers(div.get(), globals);
    else { /*TODO Non-div barriers*/ }
  }

  if (CLOptions::small())
    CLSmith::CLVariable::ParseUnusedVars();

  // Output the whole program.
  output_mgr_->Output();

  // Release any singleton instances used.
  Globals::ReleaseGlobals();
  EMIController::ReleaseEMIController();
}

void CLProgramGenerator::InitRuntimeParameters() {
  globalDim = new std::vector<unsigned int>(no_dims, 1);
  localDim = new std::vector<unsigned int>(no_dims, 1);
  std::vector<unsigned int>& globalDim = *CLSmith::globalDim;
  std::vector<unsigned int>& localDim = *CLSmith::localDim;
  std::vector<unsigned int> chosen_div;
  std::vector<unsigned int> divisors;
  for (unsigned int i = 0; i < no_dims; i++) {
    globalDim[i] = rnd_upto(std::min(max_thr_per_dim, max_threads / noThreads)) + 1;
    noThreads *= globalDim[i];
  }
  unsigned int curr_thr_p_grp;
  do {
    curr_thr_p_grp = 1;
    for (unsigned int i = 0; i < no_dims; i++) {
      get_divisors(globalDim[i], &divisors);
      localDim[i] = divisors[rnd_upto(divisors.size())];
      curr_thr_p_grp *= localDim[i];
    }
  } while (curr_thr_p_grp > max_threads_per_group);
  for (unsigned int i = 0; i < no_dims; i++)
    noGroups *= globalDim[i] / localDim[i];
}

OutputMgr *CLProgramGenerator::getOutputMgr() {
  return output_mgr_.get();
}

std::string CLProgramGenerator::get_count_prefix(const std::string& name) {
  assert(false);
  return "";
}

const unsigned int CLProgramGenerator::get_threads() {
  return noThreads;
}

const unsigned int CLProgramGenerator::get_groups() {
  return noGroups;
}

const unsigned int CLProgramGenerator::get_total_threads() {
  return noThreads * noGroups;
}

const unsigned int CLProgramGenerator::get_threads_per_group() {
  return noThreads / noGroups;
}

const std::vector<unsigned int>& CLProgramGenerator::get_global_dims() {
  return *globalDim;
}

const std::vector<unsigned int>& CLProgramGenerator::get_local_dims() {
  return *localDim;
}

const unsigned int CLProgramGenerator::get_atomic_blocks_no() {
  return CLSmith::ExpressionAtomic::get_atomic_blocks_no();
}

void CLProgramGenerator::initialize() {
}

void CLProgramGenerator::get_divisors(
    unsigned int val, std::vector<unsigned int> *divisors) {
  divisors->clear();
  divisors->push_back(1); divisors->push_back(val);
  unsigned int i;
  for (i = 2; i < sqrt(val); i++) {
    if (!(val % i)) {
      divisors->push_back(i);
      divisors->push_back(val / i);
    }
  }
  if (i * i == val)
    divisors->push_back(i);
}

}  // namespace CLSmith
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    pipe1.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkImageData.h"
#include "vtkOutputPort.h"
#include "vtkRTAnalyticSource.h"

#include "PipelineParallelism.h"

static float XFreq = 60;

// Increments XFreq of the synthetic source
void IncrementXFreq(void* sr)
{
  vtkRTAnalyticSource* source1 = reinterpret_cast<vtkRTAnalyticSource*>(sr);
  XFreq = XFreq + 10;
  source1->SetXFreq(XFreq);
}

// Pipe 1 for PipelineParallelism.
// See PipelineParallelism.cxx for more information.
void pipe1(vtkMultiProcessController* vtkNotUsed(controller),
           void* vtkNotUsed(arg))
{
  double extent = 20;
  int iextent = static_cast<int>(extent);

  // Synthetic image source.
  vtkRTAnalyticSource* source1 = vtkRTAnalyticSource::New();
  source1->SetWholeExtent (-1*iextent, iextent, -1*iextent, iextent,
                           -1*iextent, iextent );
  source1->SetCenter(0, 0, 0);
  source1->SetStandardDeviation( 0.5 );
  source1->SetMaximum( 255.0 );
  source1->SetXFreq( XFreq );
  source1->SetXMag( 10 );
  source1->SetYFreq( 30 );
  source1->SetYMag( 18 );
  source1->SetZFreq( 40 );
  source1->SetZMag( 5 );
  source1->GetOutput()->SetSpacing(2.0/extent,2.0/extent,2.0/extent);

  // Output port
  vtkOutputPort* op = vtkOutputPort::New();
  op->SetInput(source1->GetOutput());
  op->SetTag(11);
  // Turn this on for pipeline parallelism.
  op->PipelineFlagOn();
  // Called every time data is requested from the output port
  op->SetParameterMethod(IncrementXFreq, source1);
  // Process requests
  op->WaitForUpdate();

  // Cleanup
  op->Delete();
  source1->Delete();

}

<commit_msg>COMP: mods to handlge changes in ports<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    pipe1.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#include "vtkCallbackCommand.h"
#include "vtkImageData.h"
#include "vtkOutputPort.h"
#include "vtkRTAnalyticSource.h"

#include "PipelineParallelism.h"

static float XFreq = 60;

// Increments XFreq of the synthetic source
static void IncrementXFreq(vtkObject *vtkNotUsed( caller ),
                           unsigned long vtkNotUsed(eventId),
                           void *sr, void *)
{
  vtkRTAnalyticSource* source1 = reinterpret_cast<vtkRTAnalyticSource*>(sr);
  XFreq = XFreq + 10;
  source1->SetXFreq(XFreq);
}

// Pipe 1 for PipelineParallelism.
// See PipelineParallelism.cxx for more information.
void pipe1(vtkMultiProcessController* vtkNotUsed(controller),
           void* vtkNotUsed(arg))
{
  double extent = 20;
  int iextent = static_cast<int>(extent);

  // Synthetic image source.
  vtkRTAnalyticSource* source1 = vtkRTAnalyticSource::New();
  source1->SetWholeExtent (-1*iextent, iextent, -1*iextent, iextent,
                           -1*iextent, iextent );
  source1->SetCenter(0, 0, 0);
  source1->SetStandardDeviation( 0.5 );
  source1->SetMaximum( 255.0 );
  source1->SetXFreq( XFreq );
  source1->SetXMag( 10 );
  source1->SetYFreq( 30 );
  source1->SetYMag( 18 );
  source1->SetZFreq( 40 );
  source1->SetZMag( 5 );
  source1->GetOutput()->SetSpacing(2.0/extent,2.0/extent,2.0/extent);

  // Output port
  vtkOutputPort* op = vtkOutputPort::New();
  op->SetInput(source1->GetOutput());
  op->SetTag(11);

  // Called every time data is requested from the output port
  vtkCallbackCommand *cbc = vtkCallbackCommand::New();
  cbc->SetCallback(IncrementXFreq);
  cbc->SetClientData((void *)source1);
  op->AddObserver(vtkCommand::EndEvent,cbc);
  cbc->Delete();

  // Process requests
  op->WaitForUpdate();

  // Cleanup
  op->Delete();
  source1->Delete();

}

<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * GARGOYLE_PSCAND: Gargoyle Port Scan Detector
 *
 * Program to set some config key/val pairs for use across all daemons
 *
 * Copyright (c) 2017, Bayshore Networks, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that
 * the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
 * following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
 * following disclaimer in the documentation and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
 * products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *****************************************************************************/
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
#include <fstream>

#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "gargoyle_config_vals.h"

int main () {

	std::cout << GARGOYLE_VERSION << std::endl;
	std::cout << GARGOYLE_CHAIN_NAME << std::endl;

	std::map<std::string,int> mymap;

	int scand_ix = 6665;
	mymap.insert(std::pair<std::string,int>("gargoyle_pscand", scand_ix));

	int pscand_analysis_ix = 6666;
	mymap.insert(std::pair<std::string,int>("gargoyle_pscand_analysis", pscand_analysis_ix));

	int pscand_monitor_ix = 6667;
	mymap.insert(std::pair<std::string,int>("gargoyle_pscand_monitor", pscand_monitor_ix));

	int mymax = pscand_monitor_ix;

	int n;
	char cmd[100];

	std::string data;
	FILE * stream;

	size_t DEST_BUF_SZ = 1024;
	char *dest;
	dest = (char*) malloc (DEST_BUF_SZ+1);
	bool good = true;

	for (std::map<std::string,int>::iterator mit=mymap.begin(); mit!=mymap.end(); ++mit) {

		//std::cout << mit->first << " => " << mit->second << '\n';
		*cmd = 0;
		*dest = 0;
		data = "";

		snprintf(cmd, 100, "%s%d", "netstat -luan |grep :", mit->second);
		//std::cout << cmd << std::endl;

		stream = popen(cmd, "r");
		if (stream) {
			while (!feof(stream)) {
				if (fgets(dest, DEST_BUF_SZ, stream) != NULL)
					data.append(dest);
			}
			pclose(stream);
		}

		if (data.size() > 0) {

			good = false;
			while (good == false) {
				mymax++;
				std::cout << mymax << std::endl;
				data = "";

				snprintf(cmd, 100, "%s%d", "netstat -luan |grep :", mymax);

				stream = popen(cmd, "r");
				if (stream) {
					while (!feof(stream))
						if (fgets(dest, DEST_BUF_SZ, stream) != NULL)
							data.append(dest);
					pclose(stream);
				}
				if (!data.size() > 0) {
					good = true;
					mymap[mit->first] = mymax;
				}
			}
		}
	}

	std::ofstream myfile (".gargoyle_config");
	if (myfile.is_open()) {

		myfile << "gargoyle_chain_name:GARGOYLE_Input_Chain\n";

		for (std::map<std::string,int>::iterator mit=mymap.begin(); mit!=mymap.end(); ++mit) {
			myfile << mit->first << ":" << mit->second << '\n';
		}

		myfile.close();
	}

	free(dest);
	return 0;
}

<commit_msg>gargoyle_config - silencing some debug output<commit_after>/*****************************************************************************
 *
 * GARGOYLE_PSCAND: Gargoyle Port Scan Detector
 *
 * Program to set some config key/val pairs for use across all daemons
 *
 * Copyright (c) 2017, Bayshore Networks, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that
 * the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
 * following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
 * following disclaimer in the documentation and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
 * products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *****************************************************************************/
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
#include <fstream>

#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "gargoyle_config_vals.h"

int main () {
	/*
	std::cout << GARGOYLE_VERSION << std::endl;
	std::cout << GARGOYLE_CHAIN_NAME << std::endl;
	*/
	std::map<std::string,int> mymap;

	int scand_ix = 6665;
	mymap.insert(std::pair<std::string,int>("gargoyle_pscand", scand_ix));

	int pscand_analysis_ix = 6666;
	mymap.insert(std::pair<std::string,int>("gargoyle_pscand_analysis", pscand_analysis_ix));

	int pscand_monitor_ix = 6667;
	mymap.insert(std::pair<std::string,int>("gargoyle_pscand_monitor", pscand_monitor_ix));

	int mymax = pscand_monitor_ix;

	int n;
	char cmd[100];

	std::string data;
	FILE * stream;

	size_t DEST_BUF_SZ = 1024;
	char *dest;
	dest = (char*) malloc (DEST_BUF_SZ+1);
	bool good = true;

	for (std::map<std::string,int>::iterator mit=mymap.begin(); mit!=mymap.end(); ++mit) {

		//std::cout << mit->first << " => " << mit->second << '\n';
		*cmd = 0;
		*dest = 0;
		data = "";

		snprintf(cmd, 100, "%s%d", "netstat -luan |grep :", mit->second);
		//std::cout << cmd << std::endl;

		stream = popen(cmd, "r");
		if (stream) {
			while (!feof(stream)) {
				if (fgets(dest, DEST_BUF_SZ, stream) != NULL)
					data.append(dest);
			}
			pclose(stream);
		}

		if (data.size() > 0) {

			good = false;
			while (good == false) {
				mymax++;
				std::cout << mymax << std::endl;
				data = "";

				snprintf(cmd, 100, "%s%d", "netstat -luan |grep :", mymax);

				stream = popen(cmd, "r");
				if (stream) {
					while (!feof(stream))
						if (fgets(dest, DEST_BUF_SZ, stream) != NULL)
							data.append(dest);
					pclose(stream);
				}
				if (!data.size() > 0) {
					good = true;
					mymap[mit->first] = mymax;
				}
			}
		}
	}

	std::ofstream myfile (".gargoyle_config");
	if (myfile.is_open()) {

		//myfile << "gargoyle_chain_name:GARGOYLE_Input_Chain\n";

		for (std::map<std::string,int>::iterator mit=mymap.begin(); mit!=mymap.end(); ++mit) {
			myfile << mit->first << ":" << mit->second << '\n';
		}

		myfile.close();
	}

	free(dest);
	return 0;
}

<|endoftext|>


<commit_before>#include "ModelLoader.hpp"
#include <functional>
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>

Model ModelLoader::Load(std::vector<std::uint8_t> fileData)
{
    Assimp::Importer importer;
    const aiScene* scene = importer.ReadFileFromMemory(
                                        fileData.data(),
                                        fileData.size(),
                                        aiProcess_Triangulate | aiProcess_FlipUVs | aiProcess_GenNormals,
                                        "obj");

    if (!scene || scene->mFlags == AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode)
        return Model();

    auto processMesh = [](aiMesh* mesh, const aiScene* scene) -> Mesh
    {
        (void) scene;

        Mesh mData;
        for (std::uint32_t i = 0; i < mesh->mNumVertices; ++i)
        {
            // Vertices
            const aiVector3D& vert = mesh->mVertices[i];
            mData.vertices.push_back(vert.x);
            mData.vertices.push_back(vert.y);
            mData.vertices.push_back(vert.z);

            // Normals
            const aiVector3D& norm = mesh->mNormals[i];
            mData.normals.push_back(norm.x);
            mData.normals.push_back(norm.y);
            mData.normals.push_back(norm.z);

            // Texture coordinates
            if (mesh->mTextureCoords[0])
            {
                const aiVector3D& texCoord = mesh->mTextureCoords[0][i];
                mData.texCoords.push_back(texCoord.x);
                mData.texCoords.push_back(texCoord.y);
            }
        }

        // Indices
        for (std::uint32_t i = 0; i < mesh->mNumFaces; ++i)
        {
            aiFace face = mesh->mFaces[i];
            for (std::uint32_t j = 0; j < face.mNumIndices; ++j)
                mData.indices.push_back(face.mIndices[j]);
        }

        return mData;
    };

    std::function<Model(aiNode*, const aiScene*)> processNode =
    [&processMesh, &processNode](aiNode* node, const aiScene* scene) -> Model
    {
        Model model;

        // Process all the node's meshes
        for (std::uint32_t i = 0; i < node->mNumMeshes; ++i)
        {
            aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
            model.meshes.push_back(processMesh(mesh, scene));
        }

        // Same for its children
        for (std::uint32_t i = 0; i < node->mNumChildren; ++i)
        {
            Model childModel = processNode(node->mChildren[i], scene);
            model.meshes.insert(std::end(model.meshes), std::begin(childModel.meshes), std::end(childModel.meshes));
        }

        return model;
    };

    return processNode(scene->mRootNode, scene);
}

<commit_msg>Made performance optimizations in ModelLoader<commit_after>#include "ModelLoader.hpp"
#include <functional>
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>

Model ModelLoader::Load(std::vector<std::uint8_t> fileData)
{
    Assimp::Importer importer;
    const aiScene* scene = importer.ReadFileFromMemory(
                                        fileData.data(),
                                        fileData.size(),
                                        aiProcess_Triangulate |
                                        aiProcess_FlipUVs |
                                        aiProcess_GenNormals |
                                        aiProcess_CalcTangentSpace |
                                        aiProcess_SortByPType |
                                        aiProcess_JoinIdenticalVertices |
                                        aiProcess_ImproveCacheLocality,
                                        "obj");

    if (!scene || scene->mFlags == AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode)
        return Model();

    auto processMesh = [](aiMesh* mesh, const aiScene* scene) -> Mesh
    {
        (void) scene;

        Mesh mData;
        for (std::uint32_t i = 0; i < mesh->mNumVertices; ++i)
        {
            // Vertices
            const aiVector3D& vert = mesh->mVertices[i];
            mData.vertices.push_back(vert.x);
            mData.vertices.push_back(vert.y);
            mData.vertices.push_back(vert.z);

            // Normals
            const aiVector3D& norm = mesh->mNormals[i];
            mData.normals.push_back(norm.x);
            mData.normals.push_back(norm.y);
            mData.normals.push_back(norm.z);

            // Texture coordinates
            if (mesh->mTextureCoords[0])
            {
                const aiVector3D& texCoord = mesh->mTextureCoords[0][i];
                mData.texCoords.push_back(texCoord.x);
                mData.texCoords.push_back(texCoord.y);
            }
        }

        // Indices
        for (std::uint32_t i = 0; i < mesh->mNumFaces; ++i)
        {
            aiFace face = mesh->mFaces[i];
            for (std::uint32_t j = 0; j < face.mNumIndices; ++j)
                mData.indices.push_back(face.mIndices[j]);
        }

        return mData;
    };

    std::function<Model(aiNode*, const aiScene*)> processNode =
    [&processMesh, &processNode](aiNode* node, const aiScene* scene) -> Model
    {
        Model model;

        // Process all the node's meshes
        for (std::uint32_t i = 0; i < node->mNumMeshes; ++i)
        {
            aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
            model.meshes.push_back(processMesh(mesh, scene));
        }

        // Same for its children
        for (std::uint32_t i = 0; i < node->mNumChildren; ++i)
        {
            Model childModel = processNode(node->mChildren[i], scene);
            for (auto& mesh : childModel.meshes)
                model.meshes.push_back(std::move(mesh));
        }

        return model;
    };

    return processNode(scene->mRootNode, scene);
}

<|endoftext|>