internal static void UnpackSerializedHeap(XElement heapNode, IHeap <XElement> heap) { var elementsEnumerator = heapNode.Elements().GetEnumerator(); while (elementsEnumerator.MoveNext()) { heap.Add(XMLUtility.GuidOfAttribute(elementsEnumerator.Current), elementsEnumerator.Current); } }
private static IEnumerable <TSource> OrderByThenTakeImpl <TSource, TKey>(IEnumerable <TSource> source, int count, IHeap <TSource> heap) { foreach (var item in source) { heap.Add(item); if (heap.Count > count) { // Remove minimum/maximum value heap.Remove(); } } return(heap.ConsumeHeap().Reverse()); }
/// <summary> /// Does a generic heap test. /// </summary> /// <param name="heap">Heap to be checked.</param> /// <param name="input">Input values.</param> private static void HeapTest <Value>(IHeap <Value, Value> heap, List <Value> input) where Value : IComparable { List <Value> sortedInput = new List <Value>(input); sortedInput.Sort(); input.ForEach(number => heap.Add(number, number)); Assert.AreEqual(input.Count, heap.GetSize()); Assert.AreEqual(sortedInput[0], heap.GetMinKey()); heap.Clear(); Assert.AreEqual(0, heap.GetSize()); input.ForEach(number => heap.Add(number, number)); List <Value> result = new List <Value>(); while (heap.GetSize() != 0) { result.Add(heap.RemoveMin()); } Assert.IsTrue(CollectionsEquality.Equals(sortedInput, result)); }
public override bool Add(T o) { bool added = true; elements.Add(o); while (Count > Capacity()) { object dumped = elements.ExtractMin(); if (dumped.Equals(o)) { added = false; } } return(added); }
/// <summary> /// Inserts all goal conditions of the corresponding pattern to fringe. I.e. fixes the goal values and generates all combinations /// for the rest of variables by the method divide-and-conquer. /// </summary> /// <param name="fringe">Fringe.</param> /// <param name="goalConditions">Goal conditions.</param> /// <param name="cost">Current cost.</param> /// <param name="pattern">Requested pattern.</param> /// <param name="currentVariableIndex">Current variable index.</param> /// <param name="values">Generated values.</param> private void InsertPatternConditions(IHeap <double, ISimpleConditions> fringe, ISimpleConditions goalConditions, double cost, int[] pattern, int currentVariableIndex, List <int> values) { if (values.Count == pattern.Length) { Conditions conditions = new Conditions(); int i = 0; foreach (var item in pattern) { conditions.Add(new Assignment(item, values[i])); i++; } fringe.Add(cost, conditions); return; } int currentVariable = pattern[currentVariableIndex]; int constrainedGoalValue; if (goalConditions.IsVariableConstrained(currentVariable, out constrainedGoalValue)) { values.Add(constrainedGoalValue); InsertPatternConditions(fringe, goalConditions, cost, pattern, currentVariableIndex + 1, values); values.RemoveAt(values.Count - 1); } else { for (int i = 0; i < Problem.Variables[currentVariable].GetDomainRange(); ++i) { values.Add(i); InsertPatternConditions(fringe, goalConditions, cost, pattern, currentVariableIndex + 1, values); values.RemoveAt(values.Count - 1); } } }
/// <summary> /// Returns the specified number of parses or fewer for the specified tokens. /// </summary> /// <param name="tokens">A parse containing the tokens with a single parent node.</param> /// <param name="numParses">The number of parses desired.</param> /// <returns>The specified number of parses for the specified tokens.</returns> /// <remarks> /// The nodes within the returned parses are shared with other parses and therefore their /// parent node references will not be consistent with their child node reference. /// <see cref="SharpNL.Parser.Parse.Parent"/> can be used to make the parents consistent with a /// particular parse, but subsequent calls to this property can invalidate the results of earlier /// calls. /// </remarks> public Parse[] Parse(Parse tokens, int numParses) { if (createDerivationString) { tokens.Derivation = new StringBuilder(); } odh.Clear(); ndh.Clear(); completeParses.Clear(); var derivationStage = 0; //derivation length var maxDerivationLength = 2 * tokens.ChildCount + 3; odh.Add(tokens); Parse guess = null; double minComplete = 2; double bestComplete = -100000; //approximating -infinity/0 in ln domain while (odh.Size() > 0 && (completeParses.Size() < M || odh.First().Probability < minComplete) && derivationStage < maxDerivationLength) { ndh = new ListHeap <Parse>(K); var derivationRank = 0; // foreach derivation for (var pi = odh.GetEnumerator(); pi.MoveNext() && derivationRank < K; derivationRank++) { var tp = pi.Current; //TODO: Need to look at this for K-best parsing cases /* * if (tp.getProb() < bestComplete) { //this parse and the ones which follow will never win, stop advancing. * break; * } */ if (guess == null && derivationStage == 2) { guess = tp; } #if DEBUG if (debugOn) { Console.Out.WriteLine(derivationStage + " " + derivationRank + " " + tp.Probability); Console.Out.WriteLine(tp.ToString()); Console.Out.WriteLine(); } #endif Parse[] nd; if (derivationStage == 0) { nd = AdvanceTags(tp); } else if (derivationStage == 1) { nd = AdvanceChunks(tp, ndh.Size() < K ? bestComplete : ndh.Last().Probability); } else { // i > 1 nd = AdvanceParses(tp, Q); } if (nd != null) { for (int k = 0, kl = nd.Length; k < kl; k++) { if (nd[k].Complete) { AdvanceTop(nd[k]); if (nd[k].Probability > bestComplete) { bestComplete = nd[k].Probability; } if (nd[k].Probability < minComplete) { minComplete = nd[k].Probability; } completeParses.Add(nd[k]); } else { ndh.Add(nd[k]); } } } else { if (ReportFailedParse) { Console.Error.WriteLine("Couldn't advance parse " + derivationStage + " stage " + derivationRank + "!\n"); } AdvanceTop(tp); completeParses.Add(tp); } } derivationStage++; odh = ndh; } if (completeParses.Size() == 0) { if (ReportFailedParse) { Console.Error.WriteLine("Couldn't find parse for: " + tokens); } //Parse r = (Parse) odh.first(); //r.show(); //System.out.println(); return(new[] { guess }); } if (numParses == 1) { return(new[] { completeParses.First() }); } var topParses = new List <Parse>(); while (!completeParses.IsEmpty() && topParses.Count < numParses) { var tp = completeParses.Extract(); topParses.Add(tp); //parses.remove(tp); } return(topParses.ToArray()); }
public void MaxHeap_GetFirst_SingleElement_ReturnsElement() { // Arrange _heap.Add(1); // Act var actual = _heap.GetFirst(); // Assert Assert.AreEqual(1, actual); }
private static void heapTests(int size, int removeInterval, int maxValue = -1) { Logger logger = new Logger(); if (maxValue < 0) { maxValue = size / 4; } List <IHeap <double, int> > testSubjects = new List <IHeap <double, int> >(); List <string> names = new List <string>(); testSubjects.Add(new RegularBinaryHeap <int>()); names.Add("Regular Heap"); testSubjects.Add(new LeftistHeap <int>()); names.Add("Leftist Heap"); testSubjects.Add(new BinomialHeap <int>()); names.Add("Binomial Heap"); //testSubjects.Add(new SortedListHeap<int>()); //names.Add("SortedList Heap"); //testSubjects.Add(new Heaps.SingleBucket<int>(maxValue)); //names.Add("Single Bucket Heap"); //testSubjects.Add(new Heaps.RadixHeap<int>(maxValue)); //names.Add("Radix Heap"); List <List <int> > removedValues = new List <List <int> >(); List <TimeSpan> results = new List <TimeSpan>(); List <int> input = generateNonDecreasingTestInput(size, maxValue); for (int j = 0; j < testSubjects.Count; j++) { logger.Log("testing the " + names[j]); IHeap <double, int> heap = testSubjects[j]; //removedValues.Add(new List<int>()); //int index = removedValues.Count -1; DateTime start = DateTime.Now; for (int i = 0; i < size; i++) { heap.Add(input[i], input[i]); if (i % removeInterval == 0) { heap.RemoveMin(); if ((DateTime.Now - start).TotalSeconds > 120) { logger.Log(names[j] + " time limit exceeded."); break; } } } DateTime end = DateTime.Now; logger.Log("Test finished."); results.Add(end - start); testSubjects[j] = null; GC.Collect(); } /* * for (int i = 0; i < removedValues[0].Count; i++) * { * for (int j = 0; j < removedValues.Count; j++) * { * if (removedValues[j][i] != removedValues[0][i]) * { * logger.Log("chyba"); * } * } * } */ for (int i = 0; i < testSubjects.Count; i++) { logger.Log(names[i] + " " + results[i].TotalSeconds + " seconds."); } }
/// <summary> /// Returns the specified number of parses or fewer for the specified tokens. /// </summary> /// <param name="tokens">A parse containing the tokens with a single parent node.</param> /// <param name="numParses">The number of parses desired.</param> /// <returns>The specified number of parses for the specified tokens.</returns> /// <remarks> /// The nodes within the returned parses are shared with other parses and therefore their /// parent node references will not be consistent with their child node reference. /// <see cref="SharpNL.Parser.Parse.Parent"/> can be used to make the parents consistent with a /// particular parse, but subsequent calls to this property can invalidate the results of earlier /// calls. /// </remarks> public Parse[] Parse(Parse tokens, int numParses) { if (createDerivationString) tokens.Derivation = new StringBuilder(); odh.Clear(); ndh.Clear(); completeParses.Clear(); var derivationStage = 0; //derivation length var maxDerivationLength = 2*tokens.ChildCount + 3; odh.Add(tokens); Parse guess = null; double minComplete = 2; double bestComplete = -100000; //approximating -infinity/0 in ln domain while (odh.Size() > 0 && (completeParses.Size() < M || odh.First().Probability < minComplete) && derivationStage < maxDerivationLength) { ndh = new ListHeap<Parse>(K); var derivationRank = 0; // foreach derivation for (var pi = odh.GetEnumerator(); pi.MoveNext() && derivationRank < K; derivationRank++) { var tp = pi.Current; //TODO: Need to look at this for K-best parsing cases /* if (tp.getProb() < bestComplete) { //this parse and the ones which follow will never win, stop advancing. break; } */ if (guess == null && derivationStage == 2) { guess = tp; } #if DEBUG if (debugOn) { Console.Out.WriteLine(derivationStage + " " + derivationRank + " " + tp.Probability); Console.Out.WriteLine(tp.ToString()); Console.Out.WriteLine(); } #endif Parse[] nd; if (derivationStage == 0) { nd = AdvanceTags(tp); } else if (derivationStage == 1) { nd = AdvanceChunks(tp, ndh.Size() < K ? bestComplete : ndh.Last().Probability); } else { // i > 1 nd = AdvanceParses(tp, Q); } if (nd != null) { for (int k = 0, kl = nd.Length; k < kl; k++) { if (nd[k].Complete) { AdvanceTop(nd[k]); if (nd[k].Probability > bestComplete) { bestComplete = nd[k].Probability; } if (nd[k].Probability < minComplete) { minComplete = nd[k].Probability; } completeParses.Add(nd[k]); } else { ndh.Add(nd[k]); } } } else { if (ReportFailedParse) { Console.Error.WriteLine("Couldn't advance parse " + derivationStage + " stage " + derivationRank + "!\n"); } AdvanceTop(tp); completeParses.Add(tp); } } derivationStage++; odh = ndh; } if (completeParses.Size() == 0) { if (ReportFailedParse) Console.Error.WriteLine("Couldn't find parse for: " + tokens); //Parse r = (Parse) odh.first(); //r.show(); //System.out.println(); return new[] {guess}; } if (numParses == 1) { return new[] {completeParses.First()}; } var topParses = new List<Parse>(); while (!completeParses.IsEmpty() && topParses.Count < numParses) { var tp = completeParses.Extract(); topParses.Add(tp); //parses.remove(tp); } return topParses.ToArray(); }
public void Enqueue(TPriority priority, TValue value) { heap.Add(new KeyValuePair <TPriority, TValue>(priority, value)); }
/// <inheritdoc /> public void Enqueue(T item) { _heap.Add(item); }