public bool Equals(ICollection <T> x, ICollection <T> y) { if (ReferenceEquals(x, y)) { return(true); } else if (x is null) { return(CompareNullOrEmpty && y.Count == 0); } else if (y is null) { return(CompareNullOrEmpty && x.Count == 0); } if (x.Count != y.Count) { return(false); } IEnumerator <T> xEnum = x.GetEnumerator(); IEnumerator <T> yEnum = y.GetEnumerator(); while (xEnum.MoveNext() && yEnum.MoveNext()) { if (!ElementComparer.Equals(xEnum.Current, yEnum.Current)) { return(false); } } return(true); }
/// <summary> /// Creates the Root node for a new <see cref="KDTree{T}"/> given /// a set of data points and their respective stored values. /// </summary> /// /// <param name="points">The data points to be inserted in the tree.</param> /// <param name="leaves">Return the number of leaves in the Root subtree.</param> /// <param name="inPlace">Whether the given <paramref name="points"/> vector /// can be ordered in place. Passing true will change the original order of /// the vector. If set to false, all operations will be performed on an extra /// copy of the vector.</param> /// /// <returns>The Root node for a new <see cref="KDTree{T}"/> /// contained the given <paramref name="points"/>.</returns> /// protected static TNode CreateRoot(double[][] points, bool inPlace, out int leaves) { // Initial argument checks for creating the tree if (points == null) { throw new ArgumentNullException("points"); } if (!inPlace) { points = (double[][])points.Clone(); } leaves = 0; int dimensions = points[0].Length; // Create a comparer to compare individual array // elements at specified positions when sorting ElementComparer comparer = new ElementComparer(); // Call the recursive algorithm to operate on the whole array (from 0 to points.Length) TNode Root = create(points, 0, dimensions, 0, points.Length, comparer, ref leaves); // Create and return the newly formed tree return(Root); }
private static IOrderedEnumerable <T> AsSortedImplementation <T, TKey>(this IEnumerable <T> source, Func <T, TKey> keySelector, IComparer <TKey> comparer, bool descending) { source.ThrowIfNull("source"); var elementComparer = new ElementComparer <T, TKey>(keySelector, comparer ?? Comparer <TKey> .Default, descending, null); return(new OrderedEnumerableConverter <T>(source, elementComparer)); }
/// <summary> /// Teaches the stump classifier to recognize /// the class labels of the given input samples. /// </summary> /// /// <param name="inputs">The input vectors.</param> /// <param name="outputs">The class labels corresponding to each input vector.</param> /// <param name="weights">The weights associated with each input vector.</param> /// public void Learn(double[][] inputs, int[] outputs, double[] weights) { ElementComparer comparer = new ElementComparer(); double errorMinimum = Double.MaxValue; for (int i = 0; i < inputCount; i++) { comparer.Index = i; int[] indices = Matrix.Indices(0, inputs.Length); Array.Sort <int>(indices, (a, b) => inputs[a][i].CompareTo(inputs[b][i])); double error = 0.0; for (int j = 0; j < outputs.Length; j++) { int idx = indices[j]; if (outputs[idx] > 0) { error += weights[idx]; } } for (int j = 0; j < outputs.Length - 1; j++) { int idx = indices[j]; int nidx = indices[j + 1]; if (outputs[idx] < 0) { error += weights[idx]; } else { error -= weights[idx]; } double midpoint = (inputs[idx][i] + inputs[nidx][i]) / 2.0; // Compare to current best if (error < errorMinimum) { errorMinimum = error; this.featureIndex = i; this.threshold = midpoint; this.sign = +1; } if ((1.0 - error) < errorMinimum) { errorMinimum = (1.0 - error); this.featureIndex = i; this.threshold = midpoint; this.sign = -1; } } } }
private int GetElementIndex(ExportNode node, Function function, Element input, List <Element> vertices, ElementComparer comparer) { FunctionNode functionNode = _functions[function.Reference]; List <Object> parameters = function.Scope.ToList(); parameters.Add(input); Element element = _interpreter.Function <Element>(functionNode, parameters); int index = vertices.BinarySearch(element, comparer); if (index < 0) { throw new InvalidElementException(node, element); } return(index); }
private static TNode create(double[][] points, int depth, int k, int start, int length, ElementComparer comparer, ref int leaves) { if (length <= 0) { return(null); } // We will be doing sorting in place int axis = comparer.Index = depth % k; Array.Sort(points, start, length, comparer); // Middle of the input section int half = start + length / 2; // Start and end of the left branch int leftStart = start; int leftLength = half - start; // Start and end of the right branch int rightStart = half + 1; int rightLength = length - length / 2 - 1; // The median will be located halfway in the sorted array var median = points[half]; depth++; // Continue with the recursion, passing the appropriate left and right array sections var left = create(points, depth, k, leftStart, leftLength, comparer, ref leaves); var right = create(points, depth, k, rightStart, rightLength, comparer, ref leaves); if (left == null && right == null) { leaves++; } // Backtrack and create return(new TNode() { Axis = axis, Position = median, Left = left, Right = right, }); }
private static KDTreeNode<T> create(double[][] points, T[] values, int depth, int k, int start, int length, ElementComparer comparer, ref int leaves) { if (length <= 0) return null; // We will be doing sorting in place int axis = comparer.Index = depth % k; Array.Sort(points, values, start, length, comparer); // Middle of the input section int half = start + length / 2; // Start and end of the left branch int leftStart = start; int leftLength = half - start; // Start and end of the right branch int rightStart = half + 1; int rightLength = length - length / 2 - 1; // The median will be located halfway in the sorted array var median = points[half]; var value = values != null ? values[half] : default(T); depth++; // Continue with the recursion, passing the appropriate left and right array sections KDTreeNode<T> left = create(points, values, depth, k, leftStart, leftLength, comparer, ref leaves); KDTreeNode<T> right = create(points, values, depth, k, rightStart, rightLength, comparer, ref leaves); if (left == null && right == null) leaves++; // Backtrack and create return new KDTreeNode<T>() { Axis = axis, Position = median, Value = value, Left = left, Right = right, }; }
internal static KDTree <T> FromData(double[][] points, T[] values, Func <double[], double[], double> distance) { // Initial argument checks for creating the tree if (points == null) { throw new ArgumentNullException("points"); } if (distance == null) { throw new ArgumentNullException("distance"); } if (values != null && points.Length != values.Length) { throw new DimensionMismatchException("values"); } int dimensions = points[0].Length; // Create a comparer to compare individual array // elements at specified positions when sorting ElementComparer comparer = new ElementComparer(); // Since all sorting will be done in-place, we // will register the original order of values int[] idx = Matrix.Indices(0, points.Length); // Call the recursive algorithm to operate on the whole array (from 0 to points.Length) KDTreeNode <T> root = create(points, idx, values, 0, dimensions, 0, points.Length, comparer); // Restore the original ordering Array.Sort(idx, points); // Create and return the newly formed tree KDTree <T> tree = new KDTree <T>(dimensions); tree.root = root; tree.count = points.Length; tree.distance = distance; return(tree); }
/// <summary> /// Creates a comparer based on the sort configuration. /// </summary> /// <param name="sortBy">Sort configuration.</param> /// <returns>Comparer for two code elements.</returns> private IComparer <ICodeElement> CreateComparer(SortBy sortBy) { ElementComparer comparer = null; Stack <SortBy> sortByStack = new Stack <SortBy>(); while (sortBy != null) { sortByStack.Push(sortBy); sortBy = sortBy.InnerSortBy; } while (sortByStack.Count > 0) { sortBy = sortByStack.Pop(); comparer = new ElementComparer(sortBy.By, sortBy.Direction, comparer); } return(comparer); }
public LabelGraph ExportGraph(ExportNode node) { List <Object> emptyParameters = new List <Object>(); Graph graph = _interpreter.DispatchGraph(node.ExportValue, emptyParameters); string fileName = _interpreter.DispatchString(node.FileName, emptyParameters); List <int> src = new List <int>(); List <int> dst = new List <int>(); ElementComparer comparer = new ElementComparer(); List <Element> vertices = graph.Vertices.List; vertices.Sort(comparer); foreach (Element e in graph.Edges.Elements) { src.Add(GetElementIndex(node, graph.Src, e, vertices, comparer)); dst.Add(GetElementIndex(node, graph.Dst, e, vertices, comparer)); } string[,] edgeLabels = GetLabels(node.EdgeLabels, graph.Edges); string[,] vertexLabels = GetLabels(node.VertexLabels, graph.Vertices); return(new LabelGraph(fileName, src, dst, vertexLabels, edgeLabels, graph.Vertices.Elements.Count)); }
/// <summary> /// Creates the Root node for a new <see cref="KDTree{T}"/> given /// a set of data points and their respective stored values. /// </summary> /// /// <param name="points">The data points to be inserted in the tree.</param> /// <param name="values">The values associated with each point.</param> /// <param name="leaves">Return the number of leaves in the Root subtree.</param> /// <param name="inPlace">Whether the given <paramref name="points"/> vector /// can be ordered in place. Passing true will change the original order of /// the vector. If set to false, all operations will be performed on an extra /// copy of the vector.</param> /// /// <returns>The Root node for a new <see cref="KDTree{T}"/> /// contained the given <paramref name="points"/>.</returns> /// internal static KDTreeNode <T> CreateRoot(double[][] points, T[] values, bool inPlace, out int leaves) { // Initial argument checks for creating the tree if (points == null) { throw new ArgumentNullException("points"); } if (values != null && points.Length != values.Length) { throw new DimensionMismatchException("values"); } if (!inPlace) { points = (double[][])points.Clone(); if (values != null) { values = (T[])values.Clone(); } } leaves = 0; int dimensions = points[0].Length; // Create a comparer to compare individual array // elements at specified positions when sorting ElementComparer comparer = new ElementComparer(); // Call the recursive algorithm to operate on the whole array (from 0 to points.Length) KDTreeNode <T> Root = create(points, values, 0, dimensions, 0, points.Length, comparer, ref leaves); // Create and return the newly formed tree return(Root); }
public WordGraph() { Comparer = new ElementComparer (); Root = new ListDictionary (Comparer); }
public void Test002(string controlHtml, string testHtml) { var comparison = ToComparison(controlHtml, testHtml); ElementComparer.Compare(comparison, CompareResult.Different).ShouldBe(CompareResult.Different); }
public void Test001() { var comparison = ToComparison("<p>", "<p>"); ElementComparer.Compare(comparison, CompareResult.Different).ShouldBe(CompareResult.Same); }
/// <summary> /// Teaches the stump classifier to recognize /// the class labels of the given input samples. /// </summary> /// /// <param name="inputs">The input vectors.</param> /// <param name="outputs">The class labels corresponding to each input vector.</param> /// <param name="weights">The weights associated with each input vector.</param> /// public void Learn(double[][] inputs, int[] outputs, double[] weights) { ElementComparer comparer = new ElementComparer(); double errorMinimum = Double.MaxValue; for (int i = 0; i < inputCount; i++) { comparer.Index = i; int[] indices = Matrix.Indices(0, inputs.Length); Array.Sort<int>(indices, (a, b) => inputs[a][i].CompareTo(inputs[b][i])); double error = 0.0; for (int j = 0; j < outputs.Length; j++) { int idx = indices[j]; if (outputs[idx] > 0) error += weights[idx]; } for (int j = 0; j < outputs.Length - 1; j++) { int idx = indices[j]; int nidx = indices[j + 1]; if (outputs[idx] < 0) error += weights[idx]; else error -= weights[idx]; double midpoint = (inputs[idx][i] + inputs[nidx][i]) / 2.0; // Compare to current best if (error < errorMinimum) { errorMinimum = error; this.featureIndex = i; this.threshold = midpoint; this.sign = +1; } if ((1.0 - error) < errorMinimum) { errorMinimum = (1.0 - error); this.featureIndex = i; this.threshold = midpoint; this.sign = -1; } } } }
/// <summary> /// Learns a model that can map the given inputs to the given outputs. /// </summary> /// /// <param name="x">The model inputs.</param> /// <param name="y">The desired outputs associated with each <paramref name="x">inputs</paramref>.</param> /// <param name="weights">The weight of importance for each input-output pair (if supported by the learning algorithm).</param> /// /// <returns>A model that has learned how to produce <paramref name="y"/> given <paramref name="x"/>.</returns> /// public DecisionStump Learn(double[][] x, bool[] y, double[] weights = null) { if (weights == null) { weights = Vector.Create(x.Length, 1.0 / x.Length); } if (Model == null) { Model = new DecisionStump(); } var comparer = new ElementComparer(); double errorMinimum = Double.MaxValue; int numberOfVariables = x.Columns(); for (int i = 0; i < numberOfVariables; i++) { comparer.Index = i; int[] indices = Vector.Range(0, x.Length); Array.Sort(indices, (a, b) => x[a][i].CompareTo(x[b][i])); double error = 0.0; for (int j = 0; j < y.Length; j++) { int idx = indices[j]; if (y[idx]) { error += weights[idx]; } } for (int j = 0; j < y.Length - 1; j++) { int idx = indices[j]; int nidx = indices[j + 1]; if (y[idx]) { error -= weights[idx]; } else { error += weights[idx]; } double midpoint = (x[idx][i] + x[nidx][i]) / 2.0; // Compare to current best if (error < errorMinimum) { errorMinimum = error; Model.Index = i; Model.Threshold = midpoint; Model.Comparison = ComparisonKind.LessThan; } if ((1.0 - error) < errorMinimum) { errorMinimum = (1.0 - error); Model.Index = i; Model.Threshold = midpoint; Model.Comparison = ComparisonKind.GreaterThan; } } } return(Model); }
public WordGraph() { Comparer = new ElementComparer(); Root = new ListDictionary(Comparer); }
/// <summary> /// Creates a comparer based on the sort configuration. /// </summary> /// <param name="sortBy">Sort configuration.</param> /// <returns>Comparer for two code elements.</returns> private IComparer<ICodeElement> CreateComparer(SortBy sortBy) { ElementComparer comparer = null; Stack<SortBy> sortByStack = new Stack<SortBy>(); while (sortBy != null) { sortByStack.Push(sortBy); sortBy = sortBy.InnerSortBy; } while (sortByStack.Count > 0) { sortBy = sortByStack.Pop(); comparer = new ElementComparer(sortBy.By, sortBy.Direction, comparer); } return comparer; }
// Creates a new OrderedEnumerable that will sort 'source' according to 'ordering'. public OrderedEnumerable(IEnumerable <TSource> source, ElementComparer <TSource> elementComparer) { _source = source; _elementComparer = elementComparer; }
public static void ProcessFile(string fileName) { if (fileName == null) { throw new ArgumentNullException(nameof(fileName)); } var xDocument = XDocument.Load(fileName); if (xDocument.Root == null) { return; } // XML namespace. var ns = xDocument.Root.Name.Namespace; // XML node names. var itemGroupName = ns + "ItemGroup"; var referenceName = ns + "Reference"; var projectReferenceName = ns + "ProjectReference"; var comparer = new ElementComparer(); // Remove all ItemGroups. var itemGroups = xDocument.Root.Elements(itemGroupName).ToArray(); foreach (var itemGroup in itemGroups) { itemGroup.Remove(); } // ItemGroups can have a Condition. Such ItemGroups must not be merged with other // ItemGroups, but we sort the child Items. var itemGroupsWithAttributes = itemGroups.Where(e => e.HasAttributes).ToArray(); foreach (var itemGroup in itemGroupsWithAttributes) { var sortedItems = itemGroup.Elements().OrderBy(e => e, comparer).ToArray(); // ReSharper disable once CoVariantArrayConversion itemGroup.ReplaceNodes(sortedItems); xDocument.Root.Add(itemGroup); } // Get all items. Delete all comments! itemGroups = itemGroups.ToArray(); var items = itemGroups.Where(e => !e.HasAttributes) .Elements() .Where(e => e.NodeType != XmlNodeType.Comment) .ToArray(); // Create one ItemGroup with sorted Reference elements. var referenceItemGroup = new XElement( itemGroupName, items.Where(e => e.Name == referenceName) .OrderBy(e => e, comparer)); if (referenceItemGroup.HasElements) { xDocument.Root.Add(referenceItemGroup); } // Create one ItemGroup with sorted ProjectReference elements. var projectReferenceItemGroup = new XElement( itemGroupName, items.Where(e => e.Name == projectReferenceName) .OrderBy(e => e, comparer)); if (projectReferenceItemGroup.HasElements) { xDocument.Root.Add(projectReferenceItemGroup); } // Add all other items to another group. var otherItemGroup = new XElement( itemGroupName, items.Where(e => e.Name != referenceName && e.Name != projectReferenceName) .OrderBy(e => e, comparer)); if (otherItemGroup.HasElements) { xDocument.Root.Add(otherItemGroup); } // Save new file but only if the content has really changed. var oldContent = File.ReadAllBytes(fileName); byte[] newContent; using (var memoryStream = new MemoryStream()) using (var textWriter = new StreamWriter(memoryStream, Encoding.UTF8)) { xDocument.Save(textWriter); newContent = memoryStream.ToArray(); } if (oldContent.SequenceEqual(newContent)) { return; } File.WriteAllBytes(fileName, newContent); }
public IOrderedEnumerable <T> CreateOrderedEnumerable <TKey>(Func <T, TKey> keySelector, IComparer <TKey> comparer, bool descending) { var elementComparer = new ElementComparer <T, TKey>(keySelector, comparer ?? Comparer <TKey> .Default, descending, null); return(new OrderedEnumerableConverter <T>(_source, _elementComparer.Append(elementComparer))); }
public OrderedEnumerableConverter(IEnumerable <T> source, ElementComparer <T> elementComparer) { _source = source; _elementComparer = elementComparer; _descending = elementComparer.IsDescending; }
// Update is called once per frame void Update() { for (int i = 0; i < objectData.Length; i++) { if (objectData [i].isActive) { if (!(activeIndexes.Contains(i))) { activeIndexes.Add(i); } } else { if ((activeIndexes.Contains(i))) { activeIndexes.Remove(i); } } } //Default both indexes to -1, or nonexistant voltageSourceIndex = -1; groundIndex = -1; for (int i = 0; i < activeIndexes.Count; i++) { if (objectTypes [activeIndexes [i]] == "VoltageSource") { voltageSourceIndex = activeIndexes [i]; } else if (objectTypes [activeIndexes [i]] == "Ground") { groundIndex = activeIndexes [i]; } objectWorldPos[activeIndexes[i]] = new Vector3(objectData[activeIndexes[i]].world_x, objectData[activeIndexes[i]].world_y, objectData[activeIndexes[i]].world_z); objectScreenPos[activeIndexes[i]] = new Vector2(objectData[activeIndexes[i]].screen_x, objectData [activeIndexes[i]].screen_y); } elements.Clear(); //empty out the elements array if ((voltageSourceIndex >= 0) && (groundIndex >= 0)) { //lineRenderer.enabled = true; //WE HAVE A VALID CIRCUIT //Draw a line between the voltage source and ground //lineRenderer.SetPosition (0, objects [voltageSourceIndex].transform.position); //lineRenderer.SetPosition (1, objects [groundIndex].transform.position); //Calculate "path" vector p = (objectWorldPos [groundIndex] - objectWorldPos [voltageSourceIndex]); element vs = new element(objectNames [voltageSourceIndex], objectTypes [voltageSourceIndex], objectValues [voltageSourceIndex], objects [voltageSourceIndex].transform.position, Vector2.zero); element gnd = new element(objectNames [groundIndex], objectTypes [groundIndex], objectValues [groundIndex], objects [groundIndex].transform.position, new Vector2(p.magnitude, 0)); elements.Add(vs); elements.Add(gnd); Vector3 posCross = Vector3.zero; double x = -1; double y = -1; for (int i = 0; i < activeIndexes.Count; i++) { if (objectTypes[activeIndexes[i]] == "Resistor") { //If we find a resistor object //Compute the vector from the source to the resistor Vector3 b = objects[activeIndexes[i]].transform.position - objects[voltageSourceIndex].transform.position; Vector3 pCrossb = Vector3.Cross(p, b); double pDotb = Vector3.Dot(p, b); if (pCrossb != Vector3.zero && posCross == Vector3.zero) { posCross = pCrossb.normalized; } x = pDotb / p.magnitude; y = pCrossb.magnitude / p.magnitude; if (posCross != Vector3.zero && Vector3.Dot(pCrossb, posCross) < 0) { y *= -1; } element r = new element(objectNames [activeIndexes [i]], objectTypes [activeIndexes [i]], objectValues [activeIndexes [i]], objects [activeIndexes [i]].transform.position, new Vector2((float)x, (float)y)); elements.Add(r); } } } else { //lineRenderer.enabled = false; } //Elements list is all set up and ready to be used! //Comparer elementComparer = new Comparer ElementComparer elementComparer = new ElementComparer(); elements.Sort(elementComparer); //Sort all the elements based on their x value determine_lines(); for (int i = 0; i < activeIndexes.Count; i++) { if (objectTypes [activeIndexes [i]] == "Resistor") { GameObject obj = GameObject.Find(objectNames [activeIndexes [i]]); obj.GetComponentInChildren <TextMesh> ().text = ""; } } for (int i = 0; i < elements.Count; i++) { if (elements[i].getType() == "Resistor") { GameObject obj = GameObject.Find(elements [i].getName()); obj.GetComponentInChildren <TextMesh> ().text = Math.Round(elements [i].current, 2).ToString() + "A\n" + Math.Round(elements[i].voltage, 2) + "V"; } } for (int i = 0; i < lineRenderers.Length; i++) { lineRenderers[i].enabled = false; } for (int i = 0; i < lines.Count; i++) { Vector3 start = lines[i].start; Vector3 end = lines[i].end; //lineRenderers [i].SetPosition (0, start); //lineRenderers [i].SetPosition (1, end); lineRenderers [i].enabled = true; } for (int i = 0; i < electricity.Length; i++) { electricity [i].transform.position = Vector3.zero; } for (int i = 0; i < lines.Count; i++) { electricity[i].transform.position = lines [i].start; electricity [i].transform.rotation = Quaternion.FromToRotation(Vector3.forward, lines [i].end - lines [i].start); ParticleSystem ps = electricity [i].GetComponent <ParticleSystem>(); ps.startLifetime = (lines [i].end - lines [i].start).magnitude / ps.startSpeed; } Debug.Log("# of lines: " + lines.Count); }
private static (List <Vertex> vertices, List <VertexNormal> normals, List <TextureUv> uvs, List <Group> groups) ExtractOBJData(string[] lines) { var enumerable = from line in lines let split = line.Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(l => l.Trim()).ToArray() where split.Any() && !split.First().StartsWith("#") select split; var vertices = new List <Vertex>(); var normals = new List <VertexNormal>(); var uvs = new List <TextureUv>(); var currentGroup = new Group("unnamed"); var groups = new List <Group>(); var elementComparer = new ElementComparer(vertices, uvs, normals); foreach (var line in enumerable) { switch (line[0]) { case "v": Debug.Assert(line.Length == 4); var vertex = new Vertex { X = float.Parse(line[1]), Y = float.Parse(line[2]), Z = float.Parse(line[3]) }; vertices.Add(vertex); break; case "vn": Debug.Assert(line.Length == 4); normals.Add(new VertexNormal { X = float.Parse(line[1]), Y = float.Parse(line[2]), Z = float.Parse(line[3]) }); break; case "vt": uvs.Add(new TextureUv { U = float.Parse(line[1]), V = float.Parse(line[2]) //Ignore w }); break; case "g": case "o": //For the sake of bedrock, treat groups and objects as the same thing. currentGroup = new Group(line[1]); groups.Add(currentGroup); break; case "f": Debug.Assert(line.Length >= 4 && line.Length <= 5); var polygon = new Polygon(); for (var i = 1; i < line.Length; ++i) { var elements = line[i].Split("/"); var vertexIndex = int.Parse(elements[0]); var textureUvIndex = int.Parse(elements[1]); if (elements.Length > 2) { var normalIndex = int.Parse(elements[2]); polygon.AddElement(new Element(vertexIndex, textureUvIndex, normalIndex)); } else { polygon.AddElement(new Element(vertexIndex, textureUvIndex)); } } if (currentGroup.TryGetPreviousPolygon(out var lastPolygon) && lastPolygon.Vertices.Count == 3) { var uniqueElements = lastPolygon.Vertices.Except(polygon.Vertices, elementComparer).ToArray(); var missingElements = polygon.Vertices.Except(lastPolygon.Vertices, elementComparer).ToArray(); if (uniqueElements.Length == 1 && missingElements.Length == 1) { lastPolygon.RepairToQuad(missingElements.Single()); } else { currentGroup.AddPolygon(polygon); } } else { currentGroup.AddPolygon(polygon); } break; } }