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); }
void DateSet::permute(const Permutation& p) { if (p.size() != size()) throw Exception_SizesDoNotMatch(); p.permute(data_.data()); }
float Permutation::calculateKendall(const Permutation & compare) const { float score=0; vector<int> compareArray = compare.getArray(); if (getLength() != compare.getLength()) { cerr << "1stperm: " << getLength() << " 2ndperm: " << compare.getLength() << endl; throw runtime_error("Length of permutations not equal"); } if (getLength() == 0) { cerr << "Empty permutation" << endl; return 0; } for (size_t i=0; i<getLength(); i++) { for (size_t j=0; j<getLength(); j++) { if ((m_array[i] < m_array[j]) && (compareArray[i] > compareArray[j])) { score++; } } } score = (score / ((getLength()*getLength() - getLength()) /2 ) ); //Adjusted Kendall's tau correlates better with human judgements score = sqrt (score); score = 1 - score; return score; }
Word ThRightNormalForm::getShortWord( ) const { Word result; Permutation omega = Permutation::getHalfTwistPermutation( getRank( ) ); int power = getPower( ); if( power<0 ) { const list< Permutation >& decomp = getDecomposition( ); list<Permutation>:: const_iterator it = decomp.begin( ); for( int j=0 ; it!=decomp.end( ) ; ++it, ++j ) { int n = j - decomp.size( ) - power; if( n<0 ) { vector< int > gd = (*it).geodesic(); for( size_t t=0 ; t<gd.size() ; ++t ) result.push_back( gd[t]+1 ); } else { Permutation p = ( n%2 == 1 ? (*it).inverse() * omega : omega * (*it).inverse() ); vector<int> gd = p.geodesic(); for( int t=gd.size( )-1 ; t>=0 ; --t ) result.push_back( -gd[t]-1 ); } } Word omega_w = Word(omega.geodesicWord( )); omega_w = -omega_w; for( int j=decomp.size( ) ; j<-power ; ++j ) result = omega_w*result; } else result = getWord( ); return result; }
pair<std::vector<Permutation<element_type, rank_type>* >, std::map<string, int> > load_format_trec(string qresult){ std::string line; std::map<string, int> map_queries; std::vector<Permutation<element_type, rank_type>* > rankings; ifstream infile; infile.open(qresult.c_str()); while(infile.good() && std::getline( infile, line )){ std::vector<std::string> strs = split(line, ' '); element_type elem = atoi(&(strs[2]).c_str()[0]); rank_type pos = atoi(&(strs[3]).c_str()[0]); std::map<string, int>::iterator it = map_queries.find(strs[0]); if(it != map_queries.end()){ rankings[it->second]->addElement(elem, pos); }else{ Permutation<element_type, rank_type>* p = new perm_imp_type(); p->addElement(elem, pos); rankings.push_back(p); map_queries[strs[0]] = map_queries.size() - 1; } } infile.close(); return make_pair(rankings, map_queries); }
Word ThLeftNormalForm::getReducedWord() const { if (theOmegaPower >= 0 || theDecomposition.size() == 0) return getWord(); const auto p = -theOmegaPower; const auto d = theDecomposition.size(); const auto a = p < d ? p : d; Word result; // 1. Process omega const Permutation omega = Permutation::getHalfTwistPermutation(theRank); Word omegaWord = Word(omega.geodesicWord()); omegaWord = -omegaWord; result = omegaWord.power(p - a); // 2. Cancel omega^-1 with positive permutations auto it = theDecomposition.begin(); for (int i = 0; i < a; ++i, ++it) { auto perm = (-(*it)) * omega; if ((a - i - 1) % 2 != 0) perm = perm.flip(); result *= -Word(perm.geodesicWord()); } // 3. process the rest of positive permutations for (; it != theDecomposition.end(); ++it) { result *= Word((*it).geodesicWord()); } return result; }
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; }
void union_perm(Permutation<element_type, rank_type> &sigma, Permutation<element_type, rank_type> &tau){ for (typename Permutation<element_type, rank_type>::iterator it = tau.begin(); it != tau.end(); ++it) { sigma.addElement(it->first, sigma(it->first)); } }
Word ThRightNormalForm::getWord( ) const { Word result; vector< int > decomposition; vector< int > geodesic; list<Permutation>::const_iterator it = theDecomposition.begin( ); for( ; it!=theDecomposition.end( ) ; ++it ) { geodesic = (*it).geodesic( ); for( size_t j=0 ; j<geodesic.size( ) ; ++j ) result.push_back( geodesic[j]+1 ); } if( theOmegaPower==0 ) return result; Word omegaWord; const Permutation omega = Permutation::getHalfTwistPermutation( theRank ); geodesic = omega.geodesic( ); for( size_t i=0 ; i<geodesic.size( ) ; ++i ) omegaWord.push_back( geodesic[i]+1 ); if( theOmegaPower<0 ) omegaWord = -omegaWord; for( int i=0 ; i<abs(theOmegaPower) ; ++i ) result *= omegaWord; return result; }
void StringSet::permute(const Permutation& p) { if (size() != p.size()) throw Exception("Permutation and data are not of the same size"); p.permute(data_); }
TEST(PermutationTest, Inverse) { Permutation p = Permutation(create_image(3, 1, 2, 0)); Permutation inverse = p.inverse(); EXPECT_EQ(2, inverse(0)); EXPECT_EQ(0, inverse(1)); EXPECT_EQ(1, inverse(2)); }
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; }
void KRMB::applyTo(Permutation &p) { for (size_t i = 1; i <= k; ++i) { if (param.c[i] < param.d[i]) { p.applyReversal(param.c[i], param.d[i]); } } if (param.a < param.b) { p.applyReversal(param.a, param.b); } }
/* ************************************************************************* */ 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]; } }
pair< ThLeftNormalForm , ThLeftNormalForm > ThLeftNormalForm::cycle( ) const { if( theDecomposition.empty( ) ) return pair< ThLeftNormalForm , ThLeftNormalForm >( *this , ThLeftNormalForm( theRank ) ); ThLeftNormalForm result = *this; Permutation first = *(theDecomposition.begin( )); if( theOmegaPower%2!=0 ) first = first.flip( ); result.theDecomposition.push_back( first ); result.theDecomposition.pop_front( ); result.adjust( ); return pair< ThLeftNormalForm , ThLeftNormalForm >( result , ThLeftNormalForm(first) ); }
void calcK(vector<int> & v, int K) { Permutation perm; vector<vector<int> > vs = perm.permuteUnique(v); for (int i = 0; i < vs.size(); ++ i) { vector<int> & in = vs[i]; if (DEBUG) cout << "input: "; dump(in); if (DEBUG) cout << "all possible results: " << endl; dump(calc(in)); //if (DEBUG) cout << "results equal to " << K << ": " << endl; map<double, vector<string> > m = calc2(in); dumpMap(m, K); } }
//TODO default to HAMMING //Note: it returns the distance that is not normalised float Permutation::distance(const Permutation &permCompare, const distanceMetric_t &type) const { float score=0; //cout << "*****Permutation::distance" <<endl; //cout << "Ref:" << endl; //dump(); //cout << "Comp:" << endl; //permCompare.dump(); if (type == HAMMING_DISTANCE) { score = calculateHamming(permCompare); } else if (type == KENDALL_DISTANCE) { score = calculateKendall(permCompare); } else { throw runtime_error("Distance type not valid"); } float brevityPenalty = 1.0 - (float) permCompare.getTargetLength()/getTargetLength() ;//reflength divided by trans length if (brevityPenalty < 0.0) { score = score * exp(brevityPenalty); } //cout << "Distance type:" << type << endl; //cout << "Score: "<< score << endl; return score; }
void TestCorrectness ( bool print, const Matrix<Field>& A, const Permutation& P, const Matrix<Field>& AOrig, Int numRHS=100 ) { typedef Base<Field> Real; const Int n = AOrig.Width(); const Real eps = limits::Epsilon<Real>(); const Real oneNormA = OneNorm( AOrig ); Output("Testing error..."); // Generate random right-hand sides Matrix<Field> X; Uniform( X, n, numRHS ); auto Y( X ); const Real oneNormY = OneNorm( Y ); P.PermuteRows( Y ); lu::SolveAfter( NORMAL, A, Y ); // Now investigate the residual, ||AOrig Y - X||_oo Gemm( NORMAL, NORMAL, Field(-1), AOrig, Y, Field(1), X ); const Real infError = InfinityNorm( X ); const Real relError = infError / (eps*n*Max(oneNormA,oneNormY)); // TODO(poulson): Use a rigorous failure condition Output("||A X - Y||_oo / (eps n Max(||A||_1,||Y||_1)) = ",relError); if( relError > Real(1000) ) LogicError("Unacceptably large relative error"); }
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); }
// 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; }
pair< ThLeftNormalForm , ThLeftNormalForm > ThLeftNormalForm::decycle( ) const { if( theDecomposition.empty( ) ) return pair< ThLeftNormalForm , ThLeftNormalForm >( *this , ThLeftNormalForm( theRank ) ); ThLeftNormalForm result = *this; Permutation last = *(--theDecomposition.end( )); if( theOmegaPower%2==0 ) result.theDecomposition.push_front( last ); else result.theDecomposition.push_front( last.flip( ) ); result.theDecomposition.pop_back( ); result.adjust( ); return pair< ThLeftNormalForm , ThLeftNormalForm >( result , -ThLeftNormalForm(last) ); }
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); } }
void SymmetryGroup::computeClosure(Permutation const &v) //does this work?? { ElementContainer newOnes; newOnes.insert(v); while(!newOnes.empty()) { Permutation v=*newOnes.begin(); for(ElementContainer::const_iterator i=elements.begin();i!=elements.end();i++) { { Permutation n=i->apply(v); if(0==elements.count(n)) newOnes.insert(n); } { Permutation n=v.apply(v); if(0==elements.count(n)) newOnes.insert(n); } } newOnes.erase(v); elements.insert(v); } }
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); }
bool SystemSolver_FASTCG::solve(const SparseMatrix& A_in, Vector& x_in, const Vector& b_in) { typedef double CoeffType ; typedef Array1d<CoeffType> VectorType ; typedef SparseMatrixBCRS<CoeffType, 2, 2> MatrixType ; unsigned int N0 = A_in.n() ; std::cerr << "N0 = " << N0 << std::endl ; Permutation permutation; compute_permutation(A_in, permutation) ; MatrixType A ; ::OGF::convert_matrix(A_in, A, permutation) ; // ::OGF::compress_indices(A) ; std::cerr << "filling ratio:" << (A.filling_ratio() * 100.0) << "%" << std::endl ; if(false) { std::cerr << "Saving matrix to disk (matrix.dat)" << std::endl ; std::ofstream out("matrix.dat") ; // A.print(out) ; ::OGF::output_matrix(A, out) ; } unsigned int N = A.n() ; // Can be greater than N0 due to blocking N = QuickBLAS::aligned_size(N, sizeof(CoeffType)) ; std::cerr <<"N = " << N << std::endl ; int max_iter = (nb_iters_ == 0) ? 5 * N : nb_iters_ ; double eps = threshold_ ; std::cerr << "nb iters = " << max_iter << " threshold = " << eps << std::endl ; VectorType b(N, alignment_for_SSE2) ; VectorType x(N, alignment_for_SSE2) ; permutation.invert_permute_vector(b_in, b) ; permutation.invert_permute_vector(x_in, x) ; solve_cg(A, x, b, eps, max_iter) ; permutation.permute_vector(x, x_in) ; return true ; }
static void compute_permutation(const SparseMatrix& A, Permutation& permutation) { permutation.allocate(A.n()) ; bool RCMK = false ; if(RCMK) { SparseMatrixPatternCRS A_pattern ; ::OGF::convert_matrix(A, A_pattern) ; A_pattern.compute_RCMK_ordering(permutation) ; if(true) { std::cerr << "Bandwidth before permutation: " << A_pattern.bandwidth() << std::endl ; SparseMatrixCRS<double> A_crs ; ::OGF::convert_matrix(A, A_crs, true, permutation) ; std::cerr << "Bandwidth after permutation: " << A_crs.bandwidth() << std::endl ; } } else { permutation.load_identity() ; } }
void Permutation::invert(Permutation& result) const { // Rem: this is coherent with the convention // size()==0 <=> this is the identity permutation result.allocate(size()) ; for(index_t i=0; i<size(); i++) { result[(*this)[i]] = i ; } }
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); } }
TiledArray::detail::DistEval<typename Op::result_type, Policy> make_contract_eval( const TiledArray::detail::DistEval<LeftTile, Policy>& left, const TiledArray::detail::DistEval<RightTile, Policy>& right, TiledArray::World& world, const typename TiledArray::detail::DistEval<typename Op::result_type, Policy>::shape_type& shape, const std::shared_ptr<typename TiledArray::detail::DistEval<typename Op::result_type, Policy>::pmap_interface>& pmap, const Permutation& perm, const Op& op) { TA_ASSERT(left.range().rank() == op.left_rank()); TA_ASSERT(right.range().rank() == op.right_rank()); TA_ASSERT((perm.dim() == op.result_rank()) || !perm); // Define the impl type typedef TiledArray::detail::Summa< TiledArray::detail::DistEval<LeftTile, Policy>, TiledArray::detail::DistEval<RightTile, Policy>, Op, Policy> impl_type; // Precompute iteration range data const unsigned int num_contract_ranks = op.num_contract_ranks(); const unsigned int left_end = op.left_rank(); const unsigned int left_middle = left_end - num_contract_ranks; const unsigned int right_end = op.right_rank(); // Construct a vector TiledRange1 objects from the left- and right-hand // arguments that will be used to construct the result TiledRange. Also, // compute the fused outer dimension sizes, number of tiles and elements, // for the contraction. typename impl_type::trange_type::Ranges ranges(op.result_rank()); std::size_t M = 1ul, m = 1ul, N = 1ul, n = 1ul; std::size_t pi = 0ul; for(unsigned int i = 0ul; i < left_middle; ++i) { ranges[(perm ? perm[pi++] : pi++)] = left.trange().data()[i]; M *= left.range().extent_data()[i]; m *= left.trange().elements().extent_data()[i]; } for(std::size_t i = num_contract_ranks; i < right_end; ++i) { ranges[(perm ? perm[pi++] : pi++)] = right.trange().data()[i]; N *= right.range().extent_data()[i]; n *= right.trange().elements().extent_data()[i]; } // Compute the number of tiles in the inner dimension. std::size_t K = 1ul; for(std::size_t i = left_middle; i < left_end; ++i) K *= left.range().extent_data()[i]; // Construct the result range typename impl_type::trange_type trange(ranges.begin(), ranges.end()); // Construct the process grid TiledArray::detail::ProcGrid proc_grid(world, M, N, m, n); return TiledArray::detail::DistEval<typename Op::result_type, Policy>( std::shared_ptr<impl_type>( new impl_type(left, right, world, trange, shape, pmap, perm, op, K, proc_grid))); }
/** * 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; }