Esempio n. 1
0
        //public static IEnumerable<ISorterStage> ReplaceAtIndex(this IEnumerable<ISorterStage> source, int index,
        //    ISorterStage replacement)
        //{
        //    var lst = source.ToList();
        //    lst[index] = replacement;
        //    return lst;
        //}

        public static Tuple <bool, IPermutation> Sort(this ISorterStage stage, IPermutation perm)
        {
            var aRet = new uint[stage.Order];

            for (uint i = 0; i < stage.Order; i++)
            {
                aRet[i] = perm[i];
            }

            var wasUsed = false;

            for (uint i = 0; i < stage.Order; i++)
            {
                var m = stage[i];
                if (m > i)
                {
                    var llv = perm[i];
                    var hlv = perm[m];
                    if (llv > hlv)
                    {
                        aRet[m] = llv;
                        aRet[i] = hlv;
                        wasUsed = true;
                    }
                }
            }

            return(new Tuple <bool, IPermutation>(wasUsed, PermutationEx.MakePermutation(aRet)));
        }
Esempio n. 2
0
 public GenomeSorterConjOrbit(Guid id, IPermutation twoCycle, IPermutation conj, uint order, uint stageCount)
 {
     Id         = id;
     TwoCycle   = twoCycle;
     Conj       = conj;
     Order      = order;
     Stagecount = stageCount;
 }
Esempio n. 3
0
 public SortResult(ISorter sorter, double sortedness, bool[] stageUse,
                   ISortable sortable, IPermutation result)
 {
     Sortedness = sortedness;
     StageUse   = stageUse;
     Sortable   = sortable;
     Result     = result;
     Sorter     = sorter;
 }
Esempio n. 4
0
        public static int GetHashCode(this IPermutation perm)
        {
            uint hCode = 0;

            for (uint i = 0; i < perm.Order; i++)
            {
                hCode ^= perm[i];
            }
            return((int)hCode);
        }
Esempio n. 5
0
        public static uint SortednessSq(this IPermutation perm)
        {
            var tot = 0u;

            for (uint i = 0; i < perm.Order; i++)
            {
                tot += (uint)Math.Pow((i - perm[i]), 2);
            }
            return(tot);
        }
Esempio n. 6
0
        public static IPermutation ToInverse(this IPermutation perm)
        {
            var invs = new uint[perm.Order];

            for (uint i = 0; i < perm.Order; i++)
            {
                invs[perm[i]] = i;
            }
            return(new Permutation(order: perm.Order, terms: invs));
        }
        public override ISolution Apply(ISolution solution, Configuration configuration)
        {
            IPermutation permutation = (IPermutation)solution;
            TwoOperands  operands    = (TwoOperands)configuration;

            List <int> swapped = new List <int>(permutation.Order)
            {
                [operands.First]  = permutation.Order[operands.Second],
                [operands.Second] = permutation.Order[operands.First]
            };

            return(permutation.FetchPermutation(swapped, "swap"));
        }
Esempio n. 8
0
        /// <summary>
        /// Swaps the content of the indices according to the given permutation.
        /// </summary>
        /// <param name="permutation">The given permutation that specifies how the content should be permutated.</param>
        public void Swap(IPermutation permutation)
        {
            int[] ia = this.Indices;
            int   l = ia.Length, lp = permutation.Length, f;

            for (int i = 0x00; i < l; i++)
            {
                f = ia [i];
                if (f < lp)
                {
                    ia [i] = permutation.GetTransitionOfIndex(f);
                }
            }
        }
Esempio n. 9
0
        public static IPermutation Multiply(this IPermutation lhs, IPermutation rhs)
        {
            if (lhs.Order != rhs.Order)
            {
                throw new ArgumentException("The two Permutation must have the same Order");
            }
            var aRet = new uint[lhs.Order];

            for (uint i = 0; i < lhs.Order; i++)
            {
                aRet[i] = lhs[rhs[i]];
            }

            return(new Permutation(order: lhs.Order, terms: aRet));
        }
Esempio n. 10
0
        internal BaseSPN(ISubstitution substitution, IPermutation permutation, IKeyScheduler keyScheduler)
        {
            Substitution = substitution;
            Permutation  = permutation;
            KeyScheduler = keyScheduler;

            RoundCount           = 4;
            SubstitutionBoxCount = 4;
            BlockLength          = 16;

            if (BlockLength / SubstitutionBoxCount != Substitution.InputLength)
            {
                throw new Exception("ISubstitution is not compatible with SPN.");
            }
        }
Esempio n. 11
0
        public static bool IsEqualTo(this IPermutation lhs, IPermutation rhs)
        {
            if (lhs.Order != rhs.Order)
            {
                return(false);
            }

            for (uint i = 0; i < lhs.Order; i++)
            {
                if (lhs[i] != rhs[i])
                {
                    return(false);
                }
            }
            return(true);
        }
Esempio n. 12
0
 /// <summary>
 /// Saves "u" to the "Output"
 /// </summary>
 public static void Save(BinaryWriter Output, IPermutation u)
 {
     var type = u.GetType ();
     byte idType = 255;
     for (byte i = 0; i < Catalog.Count; i++) {
         if (type == Catalog [i]) {
             idType = i;
             break;
         }
     }
     if (idType == 255) {
         var s = String.Format ("Type {0} is not a recognized IPerms, please add it to " +
             "PermsGenericIO.Catalog", type);
         throw new ArgumentException (s);
     }
     Output.Write (idType);
     u.Save (Output);
 }
Esempio n. 13
0
        public static CompositeDictionary <IPermutation, int> GetOrbit(
            this IPermutation perm, uint maxSize = 1000)
        {
            var pd   = PermutationEx.PermutationDictionary(perm.Order);
            var cume = perm;

            for (var i = 0; i < maxSize; i++)
            {
                if (pd.ContainsKey(cume))
                {
                    return(pd);
                }

                pd.Add(cume, 1);
                cume = cume.Multiply(perm);
            }

            return(pd);
        }
Esempio n. 14
0
        public static CompositeDictionary <IPermutation, int> GetConjOrbit(
            this IPermutation perm, IPermutation conj, uint maxSize = 1000)
        {
            var pd      = PermutationEx.PermutationDictionary(perm.Order);
            var curConj = conj;
            var curRes  = perm;

            for (var i = 0; i < maxSize; i++)
            {
                if (pd.ContainsKey(curRes))
                {
                    return(pd);
                }
                pd.Add(curRes, 1);

                curRes  = perm.ConjugateBy(curConj);
                curConj = curConj.Multiply(conj);
            }

            return(pd);
        }
        public override ISolution Apply(ISolution solution, Configuration configuration)
        {
            IPermutation permutation = (IPermutation)solution;
            TwoOperands  operands    = (TwoOperands)configuration;

            List <int> shifted = new List <int>(permutation.Order);

            int shiftedItem = shifted[operands.First];

            shifted.RemoveAt(operands.First);
            if (operands.Second <= operands.First)
            {
                shifted.Insert(operands.Second, shiftedItem);
            }
            else
            {
                shifted.Insert(operands.Second - 1, shiftedItem);
            }

            return(permutation.FetchPermutation(shifted, "shift"));
        }
Esempio n. 16
0
        public override ISolution Apply(ISolution solution, Configuration configuration)
        {
            IPermutation permutation = (IPermutation)solution;
            TwoOperands  operands    = (TwoOperands)configuration;

            List <int> twoOpted;

            if (operands.First < operands.Second)
            {
                twoOpted = new List <int>(permutation.Order);
                twoOpted.Reverse(operands.First, operands.Second - operands.First + 1);
            }
            else
            {
                twoOpted = permutation.Order.GetRange(operands.First, permutation.Order.Count - operands.First);
                twoOpted.AddRange(permutation.Order.GetRange(0, operands.First));
                twoOpted.Reverse(0, operands.Second + twoOpted.Count - operands.First + 1);
            }

            return(permutation.FetchPermutation(twoOpted, "2opt"));
        }
Esempio n. 17
0
        public Sponge(int bitRate, IPermutation permutation)
        {
            if (permutation == null)
            {
                throw new ArgumentNullException("permutation");
            }

            if (bitRate <= 0 || bitRate > 1600)
            {
                throw new ArgumentOutOfRangeException("bitRate", "The bit rate must be betwen 1 and 1600, inclusive");
            }

            this.permutation = permutation;
            this.bitRate = bitRate;

            state = new[]
            {
                new ulong[] { 0, 0, 0, 0, 0 },
                new ulong[] { 0, 0, 0, 0, 0 },
                new ulong[] { 0, 0, 0, 0, 0 },
                new ulong[] { 0, 0, 0, 0, 0 },
                new ulong[] { 0, 0, 0, 0, 0 }
            };
        }
Esempio n. 18
0
        public Sponge(int bitRate, IPermutation permutation)
        {
            if (permutation == null)
            {
                throw new ArgumentNullException("permutation");
            }

            if (bitRate <= 0 || bitRate > 1600)
            {
                throw new ArgumentOutOfRangeException("bitRate", "The bit rate must be betwen 1 and 1600, inclusive");
            }

            this.permutation = permutation;
            this.bitRate     = bitRate;

            state = new[]
            {
                new ulong[] { 0, 0, 0, 0, 0 },
                new ulong[] { 0, 0, 0, 0, 0 },
                new ulong[] { 0, 0, 0, 0, 0 },
                new ulong[] { 0, 0, 0, 0, 0 },
                new ulong[] { 0, 0, 0, 0, 0 }
            };
        }
Esempio n. 19
0
 public static ISortable ToSortable(this IPermutation perm)
 {
     return(new Sortable(Guid.NewGuid(), perm.Order, perm.GetMap()));
 }
Esempio n. 20
0
 public Sponge(IPermutation permutation)
     : this(defaultBitRate, permutation)
 {
 }
Esempio n. 21
0
 /// <summary>
 /// Swaps the content of the indices according to the given permutation.
 /// </summary>
 /// <param name="permutation">The given permutation that specifies how the content should be permutated.</param>
 public void Swap(IPermutation permutation)
 {
     int[] ia = this.Indices;
     int l = ia.Length, lp = permutation.Length, f;
     for (int i = 0x00; i < l; i++) {
         f = ia [i];
         if (f < lp) {
             ia [i] = permutation.GetTransitionOfIndex (f);
         }
     }
 }
Esempio n. 22
0
 public static SortablePool OrbitSortablePool(IPermutation seed, uint maxSize)
 {
     return new SortablePool(Guid.NewGuid(),
         seed.GetOrbit(maxSize).Keys.Select(p => p.ToSortable()));
 }
Esempio n. 23
0
 public void FixtureSetUp()
 {
     TestFixtureBaseSetup();
     mockPermutation = Create<IPermutation>();
     defaultBitRate = 1024;
 }
Esempio n. 24
0
        public void Build(IList<int> seq, int sigma, PermutationBuilder perm_builder, BitmapFromBitStream bitmap_builder)
        {
            // A counting sort construction of the permutation
            var counters = new int[sigma];
            foreach (var s in seq) {
                if (s + 1 < sigma) {
                    counters [s + 1]++;
                }
            }
            for (int i = 1; i < sigma; i++) {
                counters [i] += counters [i - 1];
            }
            var n = seq.Count;
            var P = new int[n];
            for (int i = 0; i < n; i++) {
                var sym = seq [i];
                var pos = counters [sym];
                P [pos] = i;
                counters [sym] = pos + 1;
            }
            // the bitmap to save the lengths
            var lens = new BitStream32 ();
            int prevc = 0;
            foreach (var c in counters) {
                var len = c - prevc;
                prevc = c;
                lens.Write (true);
                lens.Write (false, len);
            }
            // an additional 1 to the end, to simplify source code
            lens.Write (true);

            var bb_lens = new FakeBitmap (lens);
            this.LENS = bitmap_builder(bb_lens);
            this.PERM = perm_builder(P);
        }
Esempio n. 25
0
 public void Load(BinaryReader Input)
 {
     this.PERM = GenericIO<IPermutation>.Load (Input);
     this.LENS = GenericIO<Bitmap>.Load (Input);
 }
Esempio n. 26
0
 public void Load(BinaryReader Input)
 {
     this.PERM = PermutationGenericIO.Load (Input);
     this.LENS = RankSelectGenericIO.Load (Input);
 }
Esempio n. 27
0
 public static int OrbitLengthFor(this IPermutation perm, uint maxSize = 1000)
 {
     return(GetOrbit(perm, maxSize).Count);
 }
Esempio n. 28
0
 public static uint[] GetMap(this IPermutation permutation)
 {
     return(0u.CountUp(permutation.Order)
            .Select(i => permutation[i])
            .ToArray());
 }
Esempio n. 29
0
 public static int ConjOrbitLengthFor(this IPermutation perm,
                                      IPermutation conj, uint maxSize = 1000)
 {
     return(GetConjOrbit(perm, conj, maxSize).Count);
 }
Esempio n. 30
0
        static void Main(string[] args)
        {
            //FloorplanProblem problem = new FloorplanProblem(50);
            //FloorplanSolution solution = new FloorplanSolution(problem);
            //Swap swap = new Swap(problem.Dimension);
            //Shift shift = new Shift(problem.Dimension);
            //FullLeafMove leaf = new FullLeafMove(problem.Dimension);
            //List<Operator> operations = new List<Operator> { swap, shift, leaf };



            TspProblem      problem    = new TspProblem(100);
            TspSolution     solution   = new TspSolution(problem);
            Swap            swap       = new Swap(problem.Dimension, 1);
            Shift           shift      = new Shift(problem.Dimension, 2);
            TwoOpt          twoOpt     = new TwoOpt(problem.Dimension, 3);
            List <Operator> operations = new List <Operator> {
                swap, shift, twoOpt
            };



            MultistartParameters multistartOptions = new MultistartParameters()
            {
                InstancesNumber = 1,
                OutputFrequency = 500,
            };

            LocalDescentParameters ldParameters = new LocalDescentParameters()
            {
                DetailedOutput    = true,
                Seed              = 0,
                Operators         = operations,
                IsSteepestDescent = false
            };

            SimulatedAnnealingParameters saParameters = new SimulatedAnnealingParameters()
            {
                InitProbability         = 0.3,
                TemperatureCooling      = 0.97,
                UseWeightedNeighborhood = true,
                DetailedOutput          = false,
                Seed      = 0,
                Operators = operations,
            };

            MultistartParameters ldMultistartParameters = (MultistartParameters)multistartOptions.Clone();

            ldMultistartParameters.Parameters = ldParameters;

            MultistartParameters saMultistartParameters = (MultistartParameters)multistartOptions.Clone();

            saMultistartParameters.Parameters = saParameters;

            LocalDescent       ld  = new LocalDescent(ldParameters);
            SimulatedAnnealing sa  = new SimulatedAnnealing(saParameters);
            ParallelMultistart pld = new ParallelMultistart(ldMultistartParameters);
            ParallelMultistart psa = new ParallelMultistart(saMultistartParameters);

            List <string> operators = new List <string>();

            IPermutation sol = solution;

            foreach (IPermutation s in ld.Minimize(solution))
            {
                Console.WriteLine("{0}, {1:f}s, {2}, {3}, {4}, {5}", s.CostValue, s.TimeInSeconds, s.IterationNumber, s.IsCurrentBest, s.IsFinal, sol.CostValue - s.CostValue);
                sol = s;
                operators.Add(s.OperatorTag);
            }


            //var groups = operators.GroupBy(s => s).Select(s => new { Operator = s.Key, Count = s.Count() });
            //var dictionary = groups.ToDictionary(g => g.Operator, g => g.Count);

            //foreach (var o in groups)
            //{
            //    Console.WriteLine("{0} = {1}", o.Operator, o.Count);
            //}

            Console.WriteLine("Done");
            Console.ReadLine();
        }
Esempio n. 31
0
 public static IPermutation ConjugateBy(this IPermutation perm, IPermutation conj)
 {
     return(conj.ToInverse().Multiply(perm.Multiply(conj)));
 }
Esempio n. 32
0
 public Sponge(IPermutation permutation)
     : this(defaultBitRate, permutation)
 {
 }
Esempio n. 33
0
        public void Build(IList<int> seq, int sigma, int t = 16, BitmapFromList64 bitmap_builder = null)
        {
            this.sigma = sigma;
            long n = seq.Count;
            var L = new long[n];

            var counters = new int[sigma + 1];
            // counters.Add (0, sigma); <- if ListIFS
            for (int i = 0; i < n; ++i) {
                var sym = seq [i];
                counters [sym + 1] += 1;
            }
            for (int i = 1; i <= sigma; ++i) {
                counters [i] += counters [i - 1];
            }
            for (int i = 0; i < n; ++i) {
                var sym = seq [i];
                long long_sym = n * ((long)sym) + i;
                L [counters [sym]] = long_sym;
                counters [sym] += 1;
            }
            counters = null;
            /**** slow construction ****/
            /*****
            for (int i = 0; i < n; ++i) {
                long s = seq [i];
                L [i] = n * s + i;
                //L.Add (n * s + i);
            }
            Array.Sort (L);
            *****/
            if (bitmap_builder == null) {
                bitmap_builder = BitmapBuilders.GetSArray64 ();
            }
            this.xl_bitmap = bitmap_builder (L, n * sigma);
            // now building the permutation for access
            var p = new ListGen_MRRR ();
            p.Build (this.GetNotIdxPERM (), t, null);
            this.perm = p;
        }
Esempio n. 34
0
 public static IPermutation ConjugateByRandomSingleTwoCycle(this IPermutation perm, IRando randy)
 {
     return(perm.ConjugateBy(randy.ToSingleTwoCyclePermutation(perm.Order)));
     // return perm.ConjugateBy(randy.ToFullTwoCyclePermutation(perm.Order));
 }
Esempio n. 35
0
 public static IPermutation ConjugateByRandomPermutation(this IPermutation perm, IRando randy)
 {
     return(perm.ConjugateBy(randy.ToPermutation(perm.Order)));
 }
Esempio n. 36
0
 public void FixtureSetUp()
 {
     TestFixtureBaseSetup();
     mockPermutation = Create <IPermutation>();
     defaultBitRate  = 1024;
 }
Esempio n. 37
0
 void Print1Perm(IPermutation p)
 {
     for (int i = 0; i < p.Count; ++i) {
         Console.Write ("<{0}>, ", p.Direct(i));
     }
     Console.WriteLine ("<END>");
 }
Esempio n. 38
0
 public void Load(BinaryReader Input)
 {
     this.sigma = Input.ReadInt32 ();
     this.xl_bitmap = RankSelect64GenericIO.Load (Input);
     var p = new ListGen_MRRR ();
     p.Load (Input);
     p.SetPERM (this.GetNotIdxPERM ());
     this.perm = p;
 }
Esempio n. 39
0
 public static ISorterStage ToSorterStage(this IPermutation permutation,
                                          uint stageNumber)
 {
     return(new SorterStage(permutation.Order, permutation.GetMap(), stageNumber));
 }
Esempio n. 40
0
 public void Load(BinaryReader Input)
 {
     this.N = Input.ReadInt32 ();
     int vocsize = Input.ReadInt32 ();
     this.InvIndex = new Bitmap[vocsize];
     for (int i = 0; i < vocsize; i++) {
         this.InvIndex [i] = GenericIO<Bitmap>.Load (Input);
     }
     this.Lens = GenericIO<Bitmap>.Load (Input);
     var p = new ListGen_MRRR ();
     p.Load (Input);
     p.SetPERM (this.GetNotIdxPERM ());
     this.Perm = p;
 }
Esempio n. 41
0
        /// <summary>
        /// Builds the index for the sequence
        /// </summary>
        public void Build(IList<int> sequence, int alphabet_size, int t = 16,
		                   BitmapFromList rowbuilder = null, BitmapFromBitStream lenbuilder = null)
        {
            if (rowbuilder == null) {
                rowbuilder = BitmapBuilders.GetSArray ();
            }
            if (lenbuilder == null) {
                lenbuilder = BitmapBuilders.GetGGMN_wt (12);
            }
            var invindex = new IList<int>[alphabet_size];
            for (int i = 0; i < alphabet_size; i++) {
                invindex [i] = new List<int> ();
            }
            int pos = 0;
            foreach (var c in sequence) {
                invindex [c].Add (pos);
                pos++;
            }
            pos = 0;
            this.N = sequence.Count;
            this.InvIndex = new Bitmap[alphabet_size];
            var lens = new BitStream32 ();
            for (int i = 0; i < alphabet_size; i++) {
                if (i % 1000 == 0) {
                    if (i % 10000 == 0) {
                        Console.WriteLine ();
                        Console.Write ("*** InvIndexXLBSeq {0}/{1}", i, alphabet_size);
                    } else {
                        Console.Write (", {0}", i);
                    }
                }
                this.InvIndex [i] = rowbuilder (invindex [i]);
                lens.Write (true);
                lens.Write (false, invindex [i].Count);
                invindex [i] = null;
            }
            lens.Write (true);
            Console.WriteLine ();
            Console.WriteLine ("done, now saving permutation and the Len bitmap");
            this.Lens = lenbuilder (new FakeBitmap (lens));
            var p = new ListGen_MRRR ();
            p.Build (this.GetNotIdxPERM (), t, null);
            Console.WriteLine ("done");
            this.Perm = p;
        }
Esempio n. 42
0
 public StageDimer(IPermutation stage1, IPermutation stage2, IPermutation modifier)
 {
     Stage1   = stage1;
     Stage2   = stage2;
     Modifier = modifier;
 }