Esempio n. 1
0
    void addSolution(const Permutation& sol)
    {
        permutations.push_back(sol);
        D_ASSERT(sol.size() == orbit_mins.size());
        debug_out(3, "SS", "Old orbit_mins:" << orbit_mins);
        for(int i : range1(sol.size()))
        {
            if(sol[i] != i)
            {
                int val1 = walkToMinimum(i);
                int val2 = walkToMinimum(sol[i]);
                int orbit_min = -1;
                if(comparison(val1, val2))
                    orbit_min = val1;
                else
                    orbit_min = val2;

                update_orbit_mins(orbit_min, val1);
                update_orbit_mins(orbit_min, val2);
                update_orbit_mins(orbit_min, i);
                update_orbit_mins(orbit_min, sol[i]);
            }
        }
        debug_out(1, "SS", "Solution found");
        debug_out(3, "SS", "Sol:" << sol);
        debug_out(3, "SS", "New orbit_mins:" << orbit_mins);
    }
Esempio n. 2
0
 Permutation operator()(Permutation lhs, Permutation rhs) const {
     assert(lhs.size() == rhs.size());
     value_type result(lhs.size());
     for (size_t i = 0; i < lhs.size(); ++i)
         result[i] = rhs[lhs[i]];
     return result;
 }
Esempio n. 3
0
set<Upair<size_t> >
permDiff(const Permutation& p1, const Permutation& p2)
{
    set<Upair<size_t> > ret;

    assert(p1.size() == p2.size());
    for (size_t i = 0; i < p1.size(); ++i)
        if (p1[i] != p2[i])
            ret.insert(Upair<size_t>(p1[i], p2[i]));

    return ret;
} 
Esempio n. 4
0
/* ************************************************************************* */
void Ordering::permuteInPlace(const Permutation& selector, const Permutation& permutation) {
  if(selector.size() != permutation.size())
    throw invalid_argument("Ordering::permuteInPlace (partial permutation version) called with selector and permutation of different sizes.");
  // Create new index the size of the permuted entries
  OrderingIndex newIndex(selector.size());
  // Permute the affected entries into the new index
  for(size_t dstSlot = 0; dstSlot < selector.size(); ++dstSlot)
    newIndex[dstSlot] = orderingIndex_[selector[permutation[dstSlot]]];
  // Put the affected entries back in the new order and fix the indices
  for(size_t slot = 0; slot < selector.size(); ++slot) {
    orderingIndex_[selector[slot]] = newIndex[slot];
    orderingIndex_[selector[slot]]->second = selector[slot];
  }
}
Esempio n. 5
0
Permutation Permutation::applyInverse(Permutation const &b)const
{
  IntVector ret(size());
  assert(size()==b.size());
  for(int i=0;i<size();i++)ret[(*this)[i]]=b[i];
  return Permutation(ret);
}
Esempio n. 6
0
ColumnPtr ColumnFixedString::permute(const Permutation & perm, size_t limit) const
{
    size_t col_size = size();

    if (limit == 0)
        limit = col_size;
    else
        limit = std::min(col_size, limit);

    if (perm.size() < limit)
        throw Exception("Size of permutation is less than required.", ErrorCodes::SIZES_OF_COLUMNS_DOESNT_MATCH);

    if (limit == 0)
        return ColumnFixedString::create(n);

    auto res = ColumnFixedString::create(n);

    Chars_t & res_chars = res->chars;

    res_chars.resize(n * limit);

    size_t offset = 0;
    for (size_t i = 0; i < limit; ++i, offset += n)
        memcpySmallAllowReadWriteOverflow15(&res_chars[offset], &chars[perm[i] * n], n);

    return std::move(res);
}
Esempio n. 7
0
void
DateSet::permute(const Permutation& p)
{
  if (p.size() != size())
    throw Exception_SizesDoNotMatch();
  p.permute(data_.data());
}
Esempio n. 8
0
void
StringSet::permute(const Permutation& p)
{
  if (size() != p.size())
    throw Exception("Permutation and data are not of the same size");

  p.permute(data_);
}
Esempio n. 9
0
void swap_rows_inverted(Permutation const& P, vector_expression<V>& v) {
    for(std::size_t i = P.size(); i != 0; --i) {
        std::size_t k = i-1;
        if(k != P(k)) {
            using std::swap;
            swap(v()(k),v()(P(k)));
        }
    }
}
Esempio n. 10
0
Permutation::Permutation(const Permutation &other)
{
  const size_t dim=other.size();
  if(dim==0) P=NULL;
  else {
    P=gsl_permutation_alloc(dim);
    gsl_permutation_memcpy(P,other.P);
  }
}
Esempio n. 11
0
		/**
		 * Composition operator ie (P1*P2)[k] = P1[P2[k]]
		 **/
		Permutation operator*(const Permutation & P2) const
			{
			MTOOLS_INSURE(_perm.size() == P2.size());
			const int l = (int)_perm.size();
			Permutation R;
			R._perm.resize(l); R._invperm.resize(l);
			for (int i = 0;i < l;i++) { R._perm[i] = _perm[P2._perm[i]]; R._invperm[i] = P2._invperm[_invperm[i]]; }
			return R;
			}
Esempio n. 12
0
/* ************************************************************************* */
void Ordering::permuteInPlace(const Permutation& permutation) {
  gttic(Ordering_permuteInPlace);
  // Allocate new index and permute in map iterators
  OrderingIndex newIndex(permutation.size());
  for(size_t j = 0; j < newIndex.size(); ++j) {
    newIndex[j] = orderingIndex_[permutation[j]]; // Assign the iterator
    newIndex[j]->second = j; // Change the stored index to its permuted value
  }
  // Swap the new index into this Ordering class
  orderingIndex_.swap(newIndex);
}
Esempio n. 13
0
void
generatePermutations(const size_t n, const size_t k, 
                     Permutation perm,
                     vector<Permutation>& rPerms)
{
    if (perm.size() == k){
        rPerms.push_back(perm);
        return;
    }
    
    perm.push_back(0);
    for (size_t i = 0; i < n; ++i){
        bool used = false;
        for (size_t m = 0; m + 1 < perm.size(); ++m)
            if (perm[m] == i){
                used = true;
                break;
            }
        if (!used){
            perm.back() = i;
            generatePermutations(n, k, perm, rPerms);
        }
    }
}
Esempio n. 14
0
ColumnPtr ColumnString::permute(const Permutation & perm, size_t limit) const
{
    size_t size = offsets.size();

    if (limit == 0)
        limit = size;
    else
        limit = std::min(size, limit);

    if (perm.size() < limit)
        throw Exception("Size of permutation is less than required.", ErrorCodes::SIZES_OF_COLUMNS_DOESNT_MATCH);

    if (limit == 0)
        return std::make_shared<ColumnString>();

    std::shared_ptr<ColumnString> res = std::make_shared<ColumnString>();

    Chars_t & res_chars = res->chars;
    Offsets_t & res_offsets = res->offsets;

    if (limit == size)
        res_chars.resize(chars.size());
    else
    {
        size_t new_chars_size = 0;
        for (size_t i = 0; i < limit; ++i)
            new_chars_size += sizeAt(perm[i]);
        res_chars.resize(new_chars_size);
    }

    res_offsets.resize(limit);

    Offset_t current_new_offset = 0;

    for (size_t i = 0; i < limit; ++i)
    {
        size_t j = perm[i];
        size_t string_offset = j == 0 ? 0 : offsets[j - 1];
        size_t string_size = offsets[j] - string_offset;

        memcpySmallAllowReadWriteOverflow15(&res_chars[current_new_offset], &chars[string_offset], string_size);

        current_new_offset += string_size;
        res_offsets[i] = current_new_offset;
    }

    return res;
}
Esempio n. 15
0
// Checks a solution satisfies all the constraints, and
// adds to the solutionStore if it is. Returns true if
// the solution is real
bool handlePossibleSolution(Problem* p, SolutionStore* ss, RBase* rbase)
{
    D_ASSERT(p->p_stack.cellCount() == p->p_stack.domainSize());
    Permutation perm = getRawPermutation(p->p_stack.domainSize());

    for(int i = 1 ; i <= perm.size(); ++i)
    {
        perm.raw(rbase->initial_permstack->val(i)) = p->p_stack.val(i);
    }
    D_ASSERT(perm.validate());
    if(!p->con_store.verifySolution(perm))
        return false;
    info_out(1, "Solution: " << perm);
    ss->addSolution(perm);
    return true;
}
Esempio n. 16
0
void
generateCombinations(const size_t n, const size_t k, 
                     Permutation perm,
                     vector<Permutation>& rPerms)
{
    if (perm.size() == k){
        rPerms.push_back(perm);
        return;
    }
    
    perm.push_back(0);
    for (size_t i = 0; i < n; ++i){
        perm.back() = i;
        generateCombinations(n, k, perm, rPerms);
    }
}
Esempio n. 17
0
ColumnPtr ColumnArray::permute(const Permutation & perm, size_t limit) const
{
	size_t size = getOffsets().size();

	if (limit == 0)
		limit = size;
	else
		limit = std::min(size, limit);

	if (perm.size() < limit)
		throw Exception("Size of permutation is less than required.", ErrorCodes::SIZES_OF_COLUMNS_DOESNT_MATCH);

	if (limit == 0)
		return std::make_shared<ColumnArray>(data);

	Permutation nested_perm(getOffsets().back());

	std::shared_ptr<ColumnArray> res = std::make_shared<ColumnArray>(data->cloneEmpty());

	Offsets_t & res_offsets = res->getOffsets();
	res_offsets.resize(limit);
	size_t current_offset = 0;

	for (size_t i = 0; i < limit; ++i)
	{
		for (size_t j = 0; j < sizeAt(perm[i]); ++j)
			nested_perm[current_offset + j] = offsetAt(perm[i]) + j;
		current_offset += sizeAt(perm[i]);
		res_offsets[i] = current_offset;
	}

	if (current_offset != 0)
		res->data = data->permute(nested_perm, current_offset);

	return res;
}
Esempio n. 18
0
static inline
Permutation identity(Permutation::Composition, Permutation a) {
    return Permutation(a.size());
}
Esempio n. 19
0
int main(int argc, char *argv[])
{
    vector<HeuristicChooseReversal *> hcr_seq;

    /* Set random seed */
    unsigned long seed = mix(clock(), time(NULL), getpid());

    /* Set random seed */
    srand(seed);

    /* Exact Unitaty Parameters */
    ofstream fout;

    /* Time results */
    timestamp_t time_begin;
    timestamp_t time_end;
    time_begin = get_timestamp();

    /* Log result file */
    ostream *logOut = NULL;
    ostream *logTime = NULL;

    /* Check essential parameters */
    // TODO: start to use parameter names instead of parameter sequence, ex: -p 1,2,4...
    if (argc < 7) {
        printf("Usage:\n");
        printf("lwr_test_metaheuristic permutation number_of_iteration inversion_limit frame_limit is_signed cost_function {-r=[[...]]}.\n\n");
        printf("Parameters description:\n");
        printf(" 1. permutation: the input permutation.\n\n");
        printf(" 2. number_of_iteration: number of iterations that will\n");
            printf("be performed by the Metaheuristic.\n\n");
        printf(" 3. inversion_limit: limit (upper bound) for the number of inversions\n");
            printf("that will be selected at each iteration of the heuristic for building solutions.\n\n");
        printf(" 4. frame_limit: percentege (in the interval (0,100]) of frames that \n");
            printf("will be selected at each iteration of the Metaheuristic.\n\n");
        printf(" 5. is_signed: 1 if the input permutation is signed, 0 otherwise.\n\n");
        printf(" 6. cost_function: 1 for linear function, 2 for quadratic function and 3 logaritmic function.\n\n");
        printf(" 7. -r=[[...]]: Optional parameter to give a seed solution as a input parameter\n");

        return 0;
    }

    /* Seed result */
    Result seed_result;

    /* Permutation parameters */
    parameter perm_param;

    /* Exact Unitary parameters */
    parameter exactP;

    /* Improve parameters */

    parameter improveP;

    /* ChooseHeuristic parameters*/
    parameter hcrP;

    /* list of solvers for choose reversals */
    vector<Solver *> solver_hcr;

    string intervalMethod = "WINDOW";
    string heuristicReversalsName = "BenefitLoss";

    /* -------------------Read the parameters  From terminal----------------- */

    int p_read = 1;

    // Read the permutation's sequence
    vector<ll> perm_seq = read_seq(argv[p_read++]);

    int num_it;
    sscanf(argv[p_read++], "%d", &num_it);

    int inv_limit;
    sscanf(argv[p_read++], "%d", &inv_limit);

    double frame_limit;
    sscanf(argv[p_read++], "%lf", &frame_limit);

    int is_signed;
    sscanf(argv[p_read++], "%d", &is_signed);

    int cost_function;
    sscanf(argv[p_read++], "%d", &cost_function);

    /* Construct the permutation */
    if (is_signed) {
        perm_param = getSignedParameters();
    } else {
        perm_param = getUnsignedGraspParameters();
    }
    Permutation perm = Permutation(perm_param, perm_seq);
    // makes a copy from the original input permutation and set the normal mode
    Permutation perm_orig = perm;

    // Look for a input solution
    Result input_seed_result;
    bool has_input_seed_result = false;
    if (p_read < argc) {
        string solution = string(argv[p_read++]);
        if (solution.substr(0, 2) == "-r") {
            // in this caseheuristicName is supposed to be like -r=[[...]]
            string str_result = solution.substr(3);
	    // Alterado por Ulisses
            input_seed_result = Util::getResultFromStr(str_result.c_str(), cost_function);
            has_input_seed_result = true;

            Permutation perm_copy = perm;
            bool valid = Solver::validateResult(perm_copy, input_seed_result, cout);
            if (!valid) {
                cout<<"Invalid input solution."<<endl;
                exit(1);
            }
        }
    }


    /* -------------Check if the permutation is already sorted--------------- */
    if (perm.isSorted(1, perm.size())) {
        Result::printResult(seed_result, cout);
        cout<<endl;
        return 0;
    }

    /* ----------------------- Set Default Parameters ----------------------- */
 
    parameter default_parameters = getDefaultParameters();

    /* Set the output for results logging */
    if (p_read < argc) {
        logOut = new ofstream(argv[p_read++], std::ofstream::out|ofstream::app);
    }
    if (p_read < argc) {
        logTime = new ofstream(argv[p_read++], std::ofstream::out|ofstream::app);
    }

    /* Look for Parameters */
    string type;
    parameter::iterator it;
    for (it = default_parameters.begin(); it != default_parameters.end(); it++) {
        pair<string, string> p = getParameterPair(it->F);
        string type = p.F;
        string name = p.S;
        double value = it->S;
        // get Num selected rev
        if (type == "HCR") {
            hcrP[name] = value;
        } else if (type == "IMP") {
            improveP[name] = value;
        } else if (type == "BUILD_SOLUTION") {
            exactP[name] = value;
        }
        p_read++;
    }
    /* Look for the unsigned mode */
    improveP["UNSIGNED"] = !is_signed;

    /* Create log file */
    //ofstream log_out("log_test_signed.txt",ios_base::app);

    /* ----------------------Set Parameters from terminal---------------------- */
    hcrP["COST_FUNCTION"]  = cost_function;
    improveP["COST_FUNCTION"]  = cost_function;
    exactP["COST_FUNCTION"]  = cost_function;

    improveP["NUM_ROUND"] = num_it;
    exactP["NUM_SELECTED_REV"] = inv_limit;

    if (frame_limit <= 0 || frame_limit > 100) {
        cerr<<"Error: frame_limit must be in the interval (0, 100]"<<endl;
        exit(1);
    }
    improveP["ROLETTE_PERCENT_DISCARD"] = (100.0 - frame_limit);


    /*---------------- Build the Choosen reversal Heuristic -------------------*/
    hcr_seq = build_hcr_seq(
      intervalMethod,
      improveP,
      hcrP,
      exactP,
      heuristicReversalsName
    );
    if (improveP["EXACT_UNITATY_LS"]) {
        solver_hcr.push_back(new ExactUnitary(exactP, hcr_seq));
    } else if (improveP["GRASP_HEURISTIC_LS"]) {
        solver_hcr.push_back(new GRASPHeuristic(exactP, hcr_seq));
    }


    /*---------------------- Build The seed solution -------------------------*/
    if (has_input_seed_result) {
        seed_result = input_seed_result;
    } else if (is_signed){
      // Alterado por Ulisses
      seed_result = sortByGRIMM(perm, true, cost_function);
    } else {
      seed_result = sortByGRIMMUnsigned(perm, NUM_IT_GRIMM_UNSIGNED, true, cost_function);
    }
        

    /*--------------------- Build Improvement Metaheuristic ------------------*/
    ImproveReversals * ir = new ImproveReversals(
        solver_hcr,
        intervalMethod,
        improveP,
        logOut
    );

    /*-------------------------- Try improve the result ----------------------*/
    Result r_improved = tryImprove(
        seed_result,
        ir,
        perm_orig,
	cost_function
     );


    /*----------------------- Validate result --------------------------------*/
    bool valid = Solver::validateResult(perm_orig, r_improved, cout);

    Result seedR = seed_result;
    //seedR.reversals = seed_result;
    seedR = Solver::calcTotalCost(seedR, cost_function);


    /*------------------------- Print the result -----------------------------*/
    if (valid) {
        Result::printResult(r_improved, cout);
        cout<<endl;
    } else {
        cout<<"ERROR";
        return 1;
    }

    /*------------------------- Print time -----------------------------------*/
    time_end = get_timestamp();
    double time_sec = get_interval_time(time_begin, time_end);

    if (logTime != NULL)
        *(logTime)<<time_sec<<endl;

    /* Clean all resources */
    for (size_t i = 0; i < solver_hcr.size(); i++) {
        delete solver_hcr[i];
    }
    solver_hcr.clear();
    if (logOut != NULL)
        delete logOut;
    delete ir;
    cleanResources();

    return valid;
}