public static double ToMetric(double value, DistanceType inputDistanceType) { double _meters = 0D; switch (inputDistanceType) { case DistanceType.MileNautical: _meters = value * GeoConstant.METERSINNMILE; break; case DistanceType.Mile: _meters = value * GeoConstant.METERSINMILE; break; case DistanceType.Yard: _meters = value * GeoConstant.METERSINYARD; break; case DistanceType.Inch: _meters = value * GeoConstant.METERSININCH; break; case DistanceType.Foot: _meters = value * GeoConstant.METERSINFOOT; break; case DistanceType.Kilometer: _meters = value * 1000D; break; case DistanceType.Meter: _meters = value; break; case DistanceType.Centimeter: _meters = value / 100D; break; case DistanceType.Millimeter: _meters = value / 1000D; break; default: throw new ArgumentException("DistanceType not supported"); } return _meters; }
/// Returns -1 if no valid targets public int FindTarget(Controller targeter, DistanceType distanceType) { int targetIndex = -1; float targetDistance = distanceType == DistanceType.NEAREST ? 0 : float.PositiveInfinity; for (int i = 0; i < bots.Count; ++i) { if (bots[i] != targeter) { if (targetIndex == -1) { targetIndex = i; targetDistance = Distance(targeter.transform.position, bots[i].transform.position); } else { float distance = Distance(targeter.transform.position, bots[i].transform.position); if (distanceType == DistanceType.NEAREST ? distance <targetDistance : distance> targetDistance) { targetIndex = i; targetDistance = distance; } } } } return(targetIndex); }
/// <summary> /// Calculate and returns the distance between to points in KM /// </summary> /// <param name="lat1">latitude of 1st point</param> /// <param name="lat2">latitude of 2nd point</param> /// <param name="long1">longitude of 1st point</param> /// <param name="long2">longitude of 2nd point</param> /// <returns>Distance in KM</returns> public double GetDistance(double lat1, double lat2, double long1, double long2, DistanceType type) { double radius = (type == DistanceType.Miles) ? earthRadiusKM : earthRadiusM; // Declare local variables double lat1Rad; double lat2Rad; double long1Rad; double long2Rad; double dlat; double dlong; // Convert angles to Radian lat1Rad = DegreeToRadian(lat1); lat2Rad = DegreeToRadian(lat2); long1Rad = DegreeToRadian(long1); long2Rad = DegreeToRadian(long2); dlat = lat2Rad - lat1Rad; dlong = long2Rad - long1Rad; double a = Math.Pow(Math.Sin(dlat / 2.0), 2.0) + Math.Cos(lat1Rad) * Math.Cos(lat2Rad) * Math.Pow(Math.Sin(dlong / 2.0), 2.0); // Calculate c - great circle distance in Radians double c = 2.0 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1.0 - a)); // Calculate Distance distance = radius * c; return distance; }
/// <summary> /// Create a OclBruteForce Matcher using the specific distance type /// </summary> /// <param name="distanceType">The distance type</param> public OclBruteForceMatcher(DistanceType distanceType) { if (distanceType == DistanceType.Hamming) { if (typeof(T) != typeof(byte)) { throw new ArgumentException("Hamming distance type requires model descriptor to be Matrix<Byte>"); } } if (typeof(T) != typeof(byte) && typeof(T) != typeof(float)) { throw new NotImplementedException(String.Format("Data type of {0} is not supported", typeof(T).ToString())); } switch (distanceType) { case (DistanceType.Hamming): _distanceType = OclMatcherDistanceType.HammingDist; break; case (DistanceType.L1): _distanceType = OclMatcherDistanceType.L1Dist; break; case (DistanceType.L2): _distanceType = OclMatcherDistanceType.L2Dist; break; default: throw new NotImplementedException(String.Format("Distance type of {0} is not implemented in GPU.", distanceType.ToString())); } _ptr = OclInvoke.oclBruteForceMatcherCreate(_distanceType); }
//private GpuMatcherDistanceType _distanceType; /// <summary> /// Create a GPUBruteForce Matcher using the specific distance type /// </summary> /// <param name="distanceType">The distance type</param> public GpuBruteForceMatcher(DistanceType distanceType) { if (distanceType == DistanceType.Hamming) { if (typeof(T) != typeof(byte)) { throw new ArgumentException("Hamming distance type requires model descriptor to be Matrix<Byte>"); } } if (typeof(T) != typeof(byte) && typeof(T) != typeof(float)) { throw new NotImplementedException(String.Format("Data type of {0} is not supported", typeof(T).ToString())); } /* * switch (distanceType) * { * case (DistanceType.Hamming): * _distanceType = GpuMatcherDistanceType.HammingDist; * break; * case (DistanceType.L1): * _distanceType = GpuMatcherDistanceType.L1Dist; * break; * case (DistanceType.L2): * _distanceType = GpuMatcherDistanceType.L2Dist; * break; * default: * throw new NotImplementedException(String.Format("Distance type of {0} is not implemented in GPU.", distanceType.ToString())); * }*/ _ptr = GpuInvoke.gpuBruteForceMatcherCreate(distanceType); }
/// <summary> /// Given an input feature, a feature space and its associated labels, and a positive integer 'k', /// Determines the 'k' nearest neighbor label for the input feature. The 'k' value corresponds /// to the number of nearest neighbors to use in the voting process. /// /// <remarks> /// "When I have this grid of data points, and I provide one additional example row, find the 'k' number /// of rows that are most similar, count up the number of occurrences of each label for each row (1 to 'k'), /// and choose the label with the highest occurrence." /// </remarks> /// <see href="http://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm" /> /// </summary> /// <param name="distanceType">The type of equation to use when measuring the distance between each data point</param> /// <param name="input">The matrix row to input; must have the same number of columns as the feature space</param> /// <param name="featureSpace">The feature space matrix; everything we know</param> /// <param name="labels">The results for each feature space row; what we call each collection of data points</param> /// <param name="k">The number of nearest neighbors to include in the voting; the label with the most occurrences in 'k' neighbors wins</param> /// <returns></returns> public static string Classify(DistanceType distanceType, Number[] input, Matrix featureSpace, IList<string> labels, int k) { if (labels.Count() != featureSpace.Rows) { throw new ArgumentException("The number of labels must match the number of rows of data in the feature space", "labels"); } var distances = CalculateDistances(distanceType, featureSpace, input); var nearestNeighbors = distances.OrderByDescending(d => d.Value).Take(k); var votes = new Dictionary<string, int>(k); foreach (var label in nearestNeighbors.Select(neighbor => labels[neighbor.Key])) { if (votes.ContainsKey(label)) { votes[label]++; } else { votes.Add(label, 1); } } var nearest = votes.OrderByDescending(v => v.Value).First().Key; return nearest; }
/// <summary> /// Match the Image feature from the observed image to the features from the model image, using brute force matcher /// </summary> /// <param name="observedFeatures">The Image feature from the observed image</param> /// <param name="k">The number of neighbors to find</param> /// <returns>The matched features</returns> public MatchedImageFeature[] MatchFeature(ImageFeature <TDescriptor>[] observedFeatures, int k) { VectorOfKeyPoint obsKpts; Matrix <TDescriptor> observedDescriptors; ImageFeature <TDescriptor> .ConvertToRaw(observedFeatures, out obsKpts, out observedDescriptors); try { DistanceType dt = typeof(TDescriptor) == typeof(Byte) ? DistanceType.Hamming : DistanceType.L2; using (Matrix <int> indices = new Matrix <int>(observedDescriptors.Rows, k)) using (Matrix <float> dists = new Matrix <float>(observedDescriptors.Rows, k)) using (BruteForceMatcher <TDescriptor> matcher = new BruteForceMatcher <TDescriptor>(dt)) { matcher.Add(_modelDescriptors); matcher.KnnMatch(observedDescriptors, indices, dists, k, null); return(ConvertToMatchedImageFeature(_modelKeyPoints, _modelDescriptors, obsKpts, observedDescriptors, indices, dists, null)); } } finally { obsKpts.Dispose(); observedDescriptors.Dispose(); } }
public void SelectNextTargetPositionAndTranslate() { distType = (DistanceType)distSample.Dequeue(); Vector2 nextTargetPosition; do { facingWall = Utility.sampleUniform(0, 4); nextTargetPosition = CalculateTargetPosition(facingWall, distType); } while(targetPosition == nextTargetPosition); targetPosition = nextTargetPosition; gainIndex = gainSample[((int)distType + 1)].Dequeue(); translate = CalculateTranslate(facingWall, gainIndex); tempTrial += 1; Debug.Log($"Start {tempTrial} ---------------------"); Debug.Log($"Facing Wall {facingWall}"); Debug.Log($"Opposite Wall {(facingWall + 2) % 4}"); Debug.Log($"Distance from opposite wall {distType}"); Debug.Log($"Applied gain {wallTranslateGain[gainIndex]}"); Debug.Log($"Next target position {targetPosition}"); Debug.Log($"End {tempTrial} ---------------------"); }
/// <summary> /// Gets the radius of the earth in the specified distance type /// </summary> /// <param name="distanceType">The distance unit to return the results in</param> /// <returns>The earth's radius</returns> protected static double GetRadius(DistanceType distanceType) { double Radius = 0; switch (distanceType) { case DistanceType.KILOMETERS: { Radius = EarthRadiusInKilometers; break; } case DistanceType.METERS: { Radius = EarthRadiusInKilometers * 1000; break; } case DistanceType.MILES: { Radius = EarthRadiusInMiles; break; } } return(Radius); }
public Graph(GraphType graphType, DistanceType distanceType) { this.graphType = graphType; this.distanceType = distanceType; nodes = new List <Node>(); edges = new List <Edge>(); }
private static List <Node> GetPathNodes(Grid grid, Point startPos, Point targetPos, DistanceType distance = DistanceType.Short, bool ignorePrices = false) { var startNode = grid.nodes[startPos.x, startPos.y]; var targetNode = grid.nodes[targetPos.x, targetPos.y]; var openSet = new List <Node>(); var closedSet = new HashSet <Node>(); openSet.Add(startNode); while (openSet.Count > 0) { var currentNode = openSet[0]; for (var i = 1; i < openSet.Count; i++) { if (openSet[i].FCost < currentNode.FCost || openSet[i].FCost == currentNode.FCost && openSet[i].hCost < currentNode.hCost) { currentNode = openSet[i]; } } openSet.Remove(currentNode); closedSet.Add(currentNode); if (currentNode == targetNode) { return(RetracePath(startNode, targetNode)); } foreach (var neighbour in grid.GetNeighbours(currentNode, distance)) { if (!neighbour.walkable || closedSet.Contains(neighbour)) { continue; } var neighbourCost = currentNode.gCost + GetDistance(currentNode, neighbour) * (ignorePrices ? 1 : (int)(10f * neighbour.price)); if (neighbourCost >= neighbour.gCost && openSet.Contains(neighbour)) { continue; } neighbour.gCost = neighbourCost; neighbour.hCost = GetDistance(neighbour, targetNode); neighbour.parent = currentNode; if (!openSet.Contains(neighbour)) { openSet.Add(neighbour); } } } return(null); }
public static AStar Create(ref byte[,] byteArray, Point start, Point end, bool asBool, DistanceType distanceType = DistanceType.Chebyshev) { if (asBool) return new BoolAStar(ref byteArray, start, end, distanceType); else return Create(ref byteArray, start, end, distanceType); }
/// <summary> /// Given an input feature, a feature space and its associated labels, and a positive integer 'k', /// Determines the 'k' nearest neighbor label for the input feature. The 'k' value corresponds /// to the number of nearest neighbors to use in the voting process. /// /// <remarks> /// "When I have this grid of data points, and I provide one additional example row, find the 'k' number /// of rows that are most similar, count up the number of occurrences of each label for each row (1 to 'k'), /// and choose the label with the highest occurrence." /// </remarks> /// <see href="http://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm" /> /// </summary> /// <param name="distanceType">The type of equation to use when measuring the distance between each data point</param> /// <param name="input">The matrix row to input; must have the same number of columns as the feature space</param> /// <param name="featureSpace">The feature space matrix; everything we know</param> /// <param name="labels">The results for each feature space row; what we call each collection of data points</param> /// <param name="k">The number of nearest neighbors to include in the voting; the label with the most occurrences in 'k' neighbors wins</param> /// <returns></returns> public static string Classify(DistanceType distanceType, Number[] input, Matrix featureSpace, IList <string> labels, int k) { if (labels.Count() != featureSpace.Rows) { throw new ArgumentException("The number of labels must match the number of rows of data in the feature space", "labels"); } var distances = CalculateDistances(distanceType, featureSpace, input); var nearestNeighbors = distances.OrderByDescending(d => d.Value).Take(k); var votes = new Dictionary <string, int>(k); foreach (var label in nearestNeighbors.Select(neighbor => labels[neighbor.Key])) { if (votes.ContainsKey(label)) { votes[label]++; } else { votes.Add(label, 1); } } var nearest = votes.OrderByDescending(v => v.Value).First().Key; return(nearest); }
private static Dictionary <int, Number> CalculateDistances(DistanceType distanceType, Matrix featureSpace, Number[] input) { var distances = new Dictionary <int, Number>(featureSpace.Rows); for (var i = 0; i < featureSpace.Rows; i++) { var features = featureSpace[i]; Number distance = 0; switch (distanceType) { case DistanceType.Euclidean: distance = Distance.Euclidean(input, features); break; case DistanceType.Manhattan: distance = Distance.Manhattan(input, features); break; case DistanceType.Minkowski: distance = Distance.Minkowski(input, features); break; case DistanceType.Hanning: distance = Distance.Hanning(input, features); break; } distances.Add(i, distance); } return(distances); }
public POICollection GetPOIList(double latitude, double longitude, int distance, DistanceType distanceType) { double calculatedDistance; //convert it back to kilometers switch (distanceType) { case DistanceType.Meters: calculatedDistance = Convert.ToDouble((double)distance / 1000); break; case DistanceType.Miles: calculatedDistance = distance / 0.621371192; break; default: calculatedDistance = distance; break; } GeoLocation myLocation = GeoLocation.FromDegrees(latitude, longitude); GeoLocation[] coordinates = myLocation.BoundingCoordinates(calculatedDistance); double north = coordinates[1].getLatitudeInDegrees(); double south = coordinates[0].getLatitudeInDegrees(); double east = coordinates[1].getLongitudeInDegrees(); double west = coordinates[0].getLongitudeInDegrees(); return GetPOIList(north, south, east, west); }
private Beacon FromCLBeacon(CLBeacon device) { Beacon beacon = new Beacon(); beacon.Minor = device.Minor.Int16Value; beacon.Major = device.Major.Int16Value; DistanceType d = DistanceType.UNKNOWN; switch (device.Proximity) { case CLProximity.Immediate: d = DistanceType.INMEDIATE; break; case CLProximity.Near: d = DistanceType.NEAR; break; case CLProximity.Far: d = DistanceType.FAR; break; case CLProximity.Unknown: break; } beacon.Distance = d; return(beacon); }
/// <summary> /// 距离判断 /// </summary> /// <param name="v1">距离检测1</param> /// <param name="v2">距离检测2</param> /// <param name="distanceType">类型</param> /// <returns></returns> public static float Distance(Vector3 v1, Vector3 v2, DistanceType distanceType, out float distanceValue) { switch (distanceType) { case DistanceType.D3D: return(distanceValue = Vector3.Distance(v1, v2)); case DistanceType.D2D: //return Vector2.Distance(v1, v2); Vector2 v21 = Camera.main.WorldToScreenPoint(v1); Vector2 v22 = Camera.main.WorldToScreenPoint(v2); float zoom = 750 / Mathf.Sqrt(Mathf.Pow(1920, 2) + Mathf.Pow(1080, 2)); zoom = Mathf.Sqrt(Mathf.Pow(Screen.height, 2) + Mathf.Pow(Screen.width, 2)) * zoom; return(distanceValue = Vector3.Distance(v21, v22) / zoom); case DistanceType.DScreen: Vector3 screen1 = MUtility.MainCamera.WorldToScreenPoint(v1); Vector3 screen2 = MUtility.MainCamera.WorldToScreenPoint(v2); return(distanceValue = Vector2.Distance(screen1, screen2)); default: return(distanceValue = -1); } }
/// <inheritdoc/> public override void UpdateContextMenu() { base.UpdateContextMenu(); deployedCableLengthMenuInfo = DistanceType.Format( cableJoint != null ? cableJoint.deployedCableLength : 0); PartModuleUtils.SetupEvent(this, ToggleExtendCableEvent, e => { e.active = linkState != LinkState.NodeIsBlocked; e.guiName = motorTargetSpeed > float.Epsilon ? StopExtendingMenuTxt : ExtendCableMenuTxt; }); PartModuleUtils.SetupEvent(this, ToggleRetractCableEvent, e => { e.active = linkState != LinkState.NodeIsBlocked; e.guiName = motorTargetSpeed < -float.Epsilon ? StopRetractingMenuTxt : RetractCableMenuTxt; }); PartModuleUtils.SetupEvent(this, InstantStretchEvent, e => { e.active = !isConnectorLocked && linkState != LinkState.NodeIsBlocked; }); PartModuleUtils.SetupEvent(this, ReleaseCableEvent, e => { e.active = linkState != LinkState.NodeIsBlocked; }); }
private void FillGraphWithEarthMapAsync(Graph graph, DistanceType distanceType) { var routes = routerFinderServices.GetRoutesDapper(); var vertexes = routerFinderServices.GetVertexesDapper(); try { if (vertexes != null) { foreach (var item in vertexes) { Node n = new Node(item.IATA3, null, Convert.ToDouble(item.Latitute), Convert.ToDouble(item.Longitude)); graph.AddNode(n); } } } catch (Exception ex) { throw new Exception(ex.Message); } if (routes != null) { foreach (var item in routes) { var nodeOrigin = graph.Nodes[item.origin]; var nodeDestination = graph.Nodes[item.Destination]; graph.AddUndirectedEdge(nodeOrigin, nodeDestination, Haversine.Distance(nodeOrigin, nodeDestination, distanceType)); } } }
public List<Distancing.Distance> GetLookupTable(DistanceType Type) { if(Type.Equals(DistanceType.AVG)) return GetLookupTable_AVG(); else return GetLookupTable_DFT(); }
public BoolAStar(ref byte[,] byteArray, Point start, Point end, DistanceType distanceType) { this.start = start; this.end = end; this.distanceType = distanceType; CreateMap(ref byteArray); }
internal static extern void cvFitLine( Arr points, DistanceType dist_type, double param, double reps, double aeps, [Out] float[] line);
/// Returns -1 if no valid targets public int FindTarget(Controller targeter, DistanceType distanceType, TargetType targetType) { int targetIndex = -1; float targetDistance = distanceType == DistanceType.NEAREST ? 0 : float.PositiveInfinity; for (int i = 0; i < bots.Count; ++i) { TargetType type = bots[i].TeamID == targeter.TeamID ? TargetType.ALLY : TargetType.ENEMY; if (bots[i] != targeter && targetType == type && !bots[i].Health.Disabled) { if (targetIndex == -1) { targetIndex = i; targetDistance = Util.Distance(targeter.transform.position, bots[i].transform.position); } else { float distance = Util.Distance(targeter.transform.position, bots[i].transform.position); if (distanceType == DistanceType.NEAREST ? distance <targetDistance : distance> targetDistance) { targetIndex = i; targetDistance = distance; } } } } return(targetIndex); }
internal static extern void cvDistTransform( Arr src, Arr dst, DistanceType distance_type, int mask_size, float[] mask, Arr labels, DistanceLabel labelType);
static void Main(string[] args) { do { Grafo graph = new Grafo(); FillGraphWithGridMap(graph); DistanceType distanceType = DistanceType.km; // Prints on the screen the distance from a city to its neighbors. // Used mainly for debug information. DistanceBetweenNodes(graph, DistanceType.km); Console.WriteLine("Essas são as cidades que você pode escolher como Origem e Destino na Roménia: \n"); // Prints on screen the cities that you can choose as Start and Destination. foreach (Node n in graph.Nodes.Cast <Node>().OrderBy(n => n.Key)) { Console.WriteLine(n.Key); } string startCity = GetStartCity(graph); string destinationCity = GetDestinationCity(graph); Node start = graph.Nodes[startCity]; Node destination = graph.Nodes[destinationCity]; // Function which tells us the exact distance between two neighbours. Func <Node, Node, double> distance = (node1, node2) => node1.Neighbors.Cast <Vertices>().Single( etn => etn.Neighbor.Key == node2.Key).Cost; // Estimation/Heuristic function (Haversine distance) // It tells us the estimated distance between the last node on a proposed path and the destination node. Func <Node, double> haversineEstimation = n => Haversine.Distance(n, destination, DistanceType.km); Caminho <Node> shortestPath = FindPath(start, destination, distance, haversineEstimation); Console.WriteLine("\nEste é o menor caminho baseado no algoritmo de busca A*:\n"); // Prints the shortest path. foreach (Caminho <Node> path in shortestPath.Reverse()) { if (path.PreviousSteps != null) { Console.WriteLine(string.Format("De {0, -15} para {1, -15} -> Custo total = {2:#.###} {3}", path.PreviousSteps.LastStep.Key, path.LastStep.Key, path.TotalCost, distanceType)); } } Console.Write("\nDeseja buscar novamente? Sim/Não? "); }while (Console.ReadLine().ToLower() == "sim"); }
internal static extern float cvCalcEMD2( Arr signature1, Arr signature2, DistanceType distance_type, CvDistanceFunction distance_func, Arr cost_matrix, Arr flow, ref float lower_bound, IntPtr userdata);
//This method to check a given sectorTime is of type distanceTypeName or not. private bool SectorTimeCheckByDistanceTypeName(double sectorTime, DistanceType distancetype) { //var distancetype = GetDistanceType(distanceTypeName); return (SectorTimeCheckByConverStringToOperator(distancetype.UpperOperator, sectorTime, distancetype.UpperSectorTime) && SectorTimeCheckByConverStringToOperator(distancetype.LowerOperator, sectorTime, distancetype.LowerSectorTime)); }
/// <summary> /// 入力画像中の値が0でないピクセルから,最も近い値が0のピクセルまでの距離を計算する /// </summary> /// <param name="src">入力画像(8ビット,シングルチャンネル,2値画像)</param> /// <param name="dst">距離計算結果をピクセル値として持つ出力画像 (32ビット浮動小数点型,シングルチャンネル)</param> /// <param name="distanceType">距離の種類.L1, L2, C か User</param> /// <param name="maskSize">距離変換マスクのサイズで,3,5,0 のいずれか. L1,C の場合,このパラメータ値は3に固定される.mask_size==0の場合,距離計算に別の近似無しアルゴリズムが用いられる.</param> /// <param name="mask">ユーザ定義の距離の場合はユーザ定義のマスク.3×3のマスクを用いる場合は2つの値(上下シフト値,斜めシフト値)を指定,5×5のマスクを用いる場合は3つの値(上下シフト値,斜めシフト値,ナイト移動シフト値(桂馬飛びのシフト値))を指定する.</param> /// <param name="labels">オプション出力.整数ラベルに変換された2次元配列で,src ,dstと同じサイズ.現在は mask_size==3 あるいは 5 のときのみに使用される.</param> /// <param name="labelType"></param> #else /// <summary> /// Calculates distance to closest zero pixel for all non-zero pixels of source image. /// </summary> /// <param name="src">Source 8-bit single-channel (binary) image. </param> /// <param name="dst">Output image with calculated distances (32-bit floating-point, single-channel). </param> /// <param name="distanceType">Type of distance. </param> /// <param name="maskSize">Size of distance transform mask; can be 3, 5 or 0. In case of CV_DIST_L1 or CV_DIST_C the parameter is forced to 3, because 3×3 mask gives the same result as 5x5 yet it is faster. When mask_size==0, a different non-approximate algorithm is used to calculate distances. </param> /// <param name="mask">User-defined mask in case of user-defined distance, it consists of 2 numbers (horizontal/vertical shift cost, diagonal shift cost) in case of 3x3 mask and 3 numbers (horizontal/vertical shift cost, diagonal shift cost, knight’s move cost) in case of 5x5 mask. </param> /// <param name="labels">The optional output 2d array of labels of integer type and the same size as src and dst, can now be used only with mask_size==3 or 5. </param> /// <param name="labelType"></param> #endif public static void DistTransform(CvArr src, CvArr dst, DistanceType distanceType, int maskSize, float[] mask, CvArr labels, DistTransformLabelType labelType) { if (src == null) throw new ArgumentNullException("src"); if (dst == null) throw new ArgumentNullException("dst"); IntPtr labelsPtr = (labels == null) ? IntPtr.Zero : labels.CvPtr; NativeMethods.cvDistTransform(src.CvPtr, dst.CvPtr, distanceType, maskSize, mask, labelsPtr, labelType); }
/// <summary> /// Khởi tạo cho thuật toán, dùng khi xây dựng cluster từ tập mẫu /// </summary> /// <param name="numCluster">Số cluster muốn tạo</param> /// <param name="samples">Các vector mẫu</param> /// <param name="distType">Loại khoảng cách</param> public Clustering(int numCluster, double[][] samples, DistanceType distType) { SampleData = new SampleSet(samples, distType); Clusters = new Cluster[numCluster]; for (int i = 0; i < numCluster; i++) { Clusters[i] = new Cluster(samples[0].Length); } HasClusterChanged = true; }
private void AddShootEffect(DistanceType type, Position origin, Position destination, ThingSet tSet) { gameMap.GetThingsInVicinity(origin, tSet); gameMap.GetThingsInVicinity(destination, tSet); foreach (Thing thing in tSet.GetThings()) { thing.AddShootEffect((byte)type, origin, destination); } }
public double CalculateDistance(Position position1, Position position2, DistanceType distanceType) { var R = (distanceType == DistanceType.Miles) ? EarthRadiusInMiles : EarthRadiusInKilometers; var dLat = angleConverter.ConvertDegreesToRadians(position2.Latitude) - angleConverter.ConvertDegreesToRadians(position1.Latitude); var dLon = angleConverter.ConvertDegreesToRadians(position2.Longitude) - angleConverter.ConvertDegreesToRadians(position1.Longitude); var a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + Math.Cos(angleConverter.ConvertDegreesToRadians(position1.Latitude)) * Math.Cos(angleConverter.ConvertDegreesToRadians(position2.Latitude)) * Math.Sin(dLon / 2) * Math.Sin(dLon / 2); var c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a)); var distance = c * R; return(Math.Round(distance, 2)); }
/// <summary> /// Uses the Haversine formula to calculate the distance between two locations /// </summary> /// <param name="pos1"></param> /// <param name="pos2"></param> /// <param name="type"></param> /// <returns></returns> public double Distance(GeocodedPosition PositionA, GeocodedPosition PositionB, DistanceType type) { double r = (type.Equals(DistanceType.Miles)) ? earthRadiusMiles : earthRadiusKilometers; double dLat = ToRadian(PositionB.Latitude - PositionA.Latitude); double dLon = ToRadian(PositionB.Longitude - PositionA.Longitude); double a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + Math.Cos(ToRadian(PositionA.Latitude)) * Math.Cos(ToRadian(PositionB.Latitude)) * Math.Sin(dLon / 2) * Math.Sin(dLon / 2); double c = 2 * Math.Asin(Math.Min(1, Math.Sqrt(a))); double d = r * c; return(d); }
private void FillGraphWithNode(Graph graph, DistanceType distanceType) { connection = new DBConnect(); listNodes = connection.getNodes(); for (int i = 0; i < listNodes.Count; i++) { Node node = new Node(listNodes[i].getNodeId(), null, listNodes[i].getLatitude(), listNodes[i].getLongitude()); graph.AddNode(node); } FillGraphWithEdge(graph); }
/// <summary> /// Renders javascript to set distance type and unit. /// </summary> /// <remarks>The distance type and unit are then added to the URL to be used on the server.</remarks> /// <param name="writer">HtmlTextWriter</param> protected override void RenderJS(HtmlTextWriter writer) { // Since this is runtime behavior do it only if there is context. RenderJS(writer, ClientCommand, "ImgTool"); writer.AddAttribute("language", "javascript"); writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/javascript"); writer.RenderBeginTag(HtmlTextWriterTag.Script); writer.WriteLine(string.Format("{0}Cmd.distanceType = '{1}';", UniqueID, DistanceType.ToString())); writer.WriteLine(string.Format("{0}Cmd.distanceUnit = '{1}';", UniqueID, DistanceUnit.ToString())); writer.RenderEndTag(); }
/// <summary> /// Distances to. /// </summary> /// <param name="lat">The lat.</param> /// <param name="lng">The LNG.</param> /// <param name="dType">Type of the d.</param> /// <returns>System.Double.</returns> public double DistanceTo(double lat, double lng, DistanceType dType) { double R = (dType == DistanceType.Miles) ? EarthRadiusInMiles : EarthRadiusInKilometers; double dLat = DegreeToRadian(lat) - DegreeToRadian(this.latitude); double dLon = DegreeToRadian(lng) - DegreeToRadian(this.longitude); double a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + Math.Cos(DegreeToRadian(this.latitude)) * Math.Cos(DegreeToRadian(lat)) * Math.Sin(dLon / 2) * Math.Sin(dLon / 2); double c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a)); double distance = c * R; return(Math.Round(distance, 2)); } // end DistanceTo
/// <summary> /// Initializes a Distance object based on a specified distance and measurement type. /// </summary> /// <param name="distance">Distance</param> /// <param name="type">Measurement type</param> /// <example> /// The following example converts meters into miles. /// <code> /// Distance distance = new Distance(1000.36, DistanceType.Meters); /// Console.WriteLine(distance.Miles); //0.62159469356 /// </code> /// </example> public Distance(double distance, DistanceType type) { bearing = 0; switch (type) { case DistanceType.Feet: feet = distance; meters = feet * 0.3048; kilometers = meters / 1000; miles = meters * 0.000621371; nauticalMiles = meters * 0.0005399565; break; case DistanceType.Kilometers: kilometers = distance; meters = kilometers * 1000; feet = meters * 3.28084; miles = meters * 0.000621371; nauticalMiles = meters * 0.0005399565; break; case DistanceType.Meters: meters = distance; kilometers = meters / 1000; feet = meters * 3.28084; miles = meters * 0.000621371; nauticalMiles = meters * 0.0005399565; break; case DistanceType.Miles: miles = distance; meters = miles * 1609.344; feet = meters * 3.28084; kilometers = meters / 1000; nauticalMiles = meters * 0.0005399565; break; case DistanceType.NauticalMiles: nauticalMiles = distance; meters = nauticalMiles * 1852.001; feet = meters * 3.28084; kilometers = meters / 1000; miles = meters * 0.000621371; break; default: kilometers = distance; meters = distance * 1000; feet = meters * 3.28084; miles = meters * 0.000621371; nauticalMiles = meters * 0.0005399565; break; } }
void FormatFixed() { #region CompactNumberType2_FormatFixed Debug.Log(DistanceType.Format(1234.5678, format: "0.0000")); // Prints: "1234.5678" Debug.Log(DistanceType.Format(1234.5678, format: "0.00")); // Prints: "1234.57" Debug.Log(DistanceType.Format(1234.5678, format: "#,##0.00")); // Prints: "1,234.57" #endregion }
/// <summary> /// Returns the distance in miles or kilometers of any two /// latitude / longitude points. /// </summary> /// <param name=”pos1″></param> /// <param name=”pos2″></param> /// <param name=”type”></param> /// <returns>Distance</returns> public double Distance(Position pos1, Position pos2, DistanceType type) { double R = (type == DistanceType.Miles) ? 3960 : 6371; double dLat = this.toRadian(pos2.Latitude - pos1.Latitude); double dLon = this.toRadian(pos2.Longitude - pos1.Longitude); double a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + Math.Cos(this.toRadian(pos1.Latitude)) * Math.Cos(this.toRadian(pos2.Latitude)) * Math.Sin(dLon / 2) * Math.Sin(dLon / 2); double c = 2 * Math.Asin(Math.Min(1, Math.Sqrt(a))); double d = R * c; return d; }
public SampleSet(double[][] input, DistanceType type) { Samples = input; DistanceToClusters = new double[input.Length]; ClusterIndices = new int[input.Length]; for(int i = 0;i < DistanceToClusters.Length;i++) { DistanceToClusters[i] = -1; ClusterIndices[i] = -1; } DistType = type; }
/// <summary> /// Returns the distance in miles or kilometers of any two /// latitude / longitude points. /// </summary> public static double DistanceBetween(XLocation pos1, XLocation pos2, DistanceType type) { double R = (type == DistanceType.Miles) ? 3960 : 6371; double dLat = _toRadian(pos2.Latitude - pos1.Latitude); double dLon = _toRadian(pos2.Longitude - pos1.Longitude); double a = Math.Sin(dLat/2)*Math.Sin(dLat/2) + Math.Cos(_toRadian(pos1.Latitude))*Math.Cos(_toRadian(pos2.Latitude))* Math.Sin(dLon/2)*Math.Sin(dLon/2); double c = 2*Math.Asin(Math.Min(1, Math.Sqrt(a))); double d = R*c; return d; }
public static float Distance(float latA, float lonA, float latB, float lonB, DistanceType type) { float R = (type == DistanceType.Miles) ? 3960 : 6371; float fLat = toRadian(latB - latA); float fLon = toRadian(lonB - lonA); float a = Mathf.Sin(fLat / 2) * Mathf.Sin(fLat / 2) + Mathf.Cos(toRadian(latA)) * Mathf.Cos(toRadian(latB)) * Mathf.Sin(fLon / 2) * Mathf.Sin(fLon / 2); float c = 2 * Mathf.Asin(Mathf.Min(1, Mathf.Sqrt(a))); float d = R * c; return d; }
/// <summary> /// Returns the distance in miles or kilometers of any two /// latitude / longitude points. /// </summary> /// <param name="pos1">The pos1.</param> /// <param name="pos2">The pos2.</param> /// <param name="type">The type.</param> /// <returns></returns> public static double Distance(Position pos1, Position pos2,DistanceType type) { double r = (type == DistanceType.Miles) ? 3960 : 6371; var dLat = ToRadian(pos2.Latitude - pos1.Latitude); var dLon = ToRadian(pos2.Longitude - pos1.Longitude); var a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + Math.Cos(ToRadian(pos1.Latitude)) *Math.Cos(ToRadian(pos2.Latitude)) * Math.Sin(dLon / 2) * Math.Sin(dLon / 2); var c = 2 * Math.Asin(Math.Min(1, Math.Sqrt(a))); var d = r * c; return d; }
public static DirectionsResponse Directions(double[] origin, double[] destination, DistanceType type, DistanceUnit unit, bool sensor) { string url = APIUrl + "directions/json"; string[] parameters = { "origin", "destination", "mode", "units", "sensor" }; string[] values = { origin[0].ToString() + "," + origin[1].ToString() , destination[0].ToString() + "," + destination[1].ToString(), type.ToString(), unit.ToString(), ((sensor) ? "true" : "false") }; ArrayList headers = new ArrayList(); string response = Utils.Request.ReadResponse(Utils.Request.Get(url, Encoding.UTF8, parameters, values, headers), Encoding.UTF8); DirectionsResponse dr = jss.Deserialize<DirectionsResponse>(response); return dr; }
/// <summary> /// Returns the distance in miles or kilometers of any two /// latitude / longitude points. /// </summary> /// <param name=”node1″></param> /// <param name=”node2″></param> /// <param name=”type”></param> /// <returns></returns> public static double Distance(Node node1, Node node2, DistanceType type) { double R = (type == DistanceType.ml) ? 3960 : 6371; double dLat = ToRadian(node2.Latitude - node1.Latitude); double dLon = ToRadian(node2.Longitude - node1.Longitude); double a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + Math.Cos(ToRadian(node1.Latitude)) * Math.Cos(ToRadian(node2.Latitude)) * Math.Sin(dLon / 2) * Math.Sin(dLon / 2); double c = 2 * Math.Asin(Math.Min(1, Math.Sqrt(a))); double d = R * c; return d; }
public Node(Point location, byte cost, Point start, Point end, DistanceType distanceType = DistanceType.Chebyshev) { this.location = location; this.cost = cost; switch (distanceType) { case DistanceType.Octile: g = OHeuristic(end); h = OHeuristic(start); break; case DistanceType.Chebyshev: g = CHeuristic(end); h = CHeuristic(start); break; case DistanceType.Manhattan: g = MHeuristic(end); h = MHeuristic(start); break; } }
internal Sartin(BrisPastPerformance pp) { _firstFraction = pp.SpeedDuringFirstFraction * Utilities.FEET_IN_A_YEARD; _secondFraction = pp.SpeedDuringSecondFraction * Utilities.FEET_IN_A_YEARD; _finalFraction = pp.SpeedDuringFinalFraction * Utilities.FEET_IN_A_YEARD; _earlyPace = pp.SpeedFromStartToSecondCall * Utilities.FEET_IN_A_YEARD; int distance = pp.DistanceInYards; if (distance <= 0) { _distanceType = DistanceType.Invalid; } else if (distance <= Utilities.YARDS_IN_A_FURLONG * 7) { _distanceType = DistanceType.Sprint; } else { _distanceType = DistanceType.Route; } }
/// <summary> /// Returns the unit abbreviation for a particular distance type (ft, km, mi, etc.) /// </summary> /// <param name="distanceType">Distance type to get abbreviation for</param> /// <returns>Two character lower case abbreviation for a distance type</returns> public static string Unit(DistanceType distanceType) { return _shortAbbrev[(int)distanceType]; }
/// <summary> /// Create a GPUBruteForce Matcher using the specific distance type /// </summary> /// <param name="distType">The distance type</param> public GpuBruteForceMatcher(DistanceType distType) { _distanceType = distType; _ptr = gpuBruteForceMatcherCreate(distType); }
/// <summary> /// Fits line to the set of 3D points using M-estimator algorithm. /// The input is vector of 3D points. /// </summary> /// <param name="distType">Distance used by the M-estimator</param> /// <param name="param">Numerical parameter ( C ) for some types of distances. /// If it is 0, an optimal value is chosen.</param> /// <param name="reps">Sufficient accuracy for the radius /// (distance between the coordinate origin and the line).</param> /// <param name="aeps">Sufficient accuracy for the angle. /// 0.01 would be a good default value for reps and aeps.</param> /// <returns>Output line parameters.</returns> public CvLine3D FitLine3D(DistanceType distType, double param, double reps, double aeps) { var line = new MatOfFloat(); Cv2.FitLine(this, line, distType, param, reps, aeps); return new CvLine3D(line.ToArray()); }
/* public List<Distancing.Distance> GetLookupTable_AVG(Axis axis) { List<Distancing.Distance> Output = new List<Distancing.Distance>(); //this pulls a distinct list of the distance points in the DB foreach (int Dist in this.LookupData.Select(d => d.Distance).Distinct()) { //decimal AvgI = (decimal)this.LookupData.Where(d => d.Distance.Equals(Dist)&& d.reciver.equals((int)axis)).Select(d => d.I).Average(); //decimal AvgQ = (decimal)this.LookupData.Where(d => d.Distance.Equals(Dist)&& d.reciver.equals((int)axis)).Select(d => d.Q).Average(); int count = this.LookupData.Where(d => d.Distance.Equals(Dist)).Count(); Output.Add(new Distancing.Distance() { Dist = Dist, I = AvgI, Q = AvgQ, NumberofReads = count }); } return Output; } */ public List<Distancing.Distance> GetLookupTable(DistanceType Type) { return GetLookupTable_DFT(); }
/// <summary> /// Create a BruteForceMatcher of the specific distance type /// </summary> /// <param name="distanceType">The distance type</param> public BruteForceMatcher(DistanceType distanceType) { _distanceType = distanceType; _ptr = CvBruteForceMatcherCreate(_distanceType); }
private static extern void CvBruteForceMatcherRelease(ref IntPtr matcher, DistanceType distanceType);
public static extern void cvDistTransform(IntPtr src, IntPtr dst, DistanceType distanceType, int mask_size, float[] user_mask, IntPtr labels);
/// <summary> /// Returns the full unit name (in English) for a particular distance time (km, ft., m) /// </summary> /// <param name="distanceType">Distance type to get abbreviation for</param> /// <returns>Lower case abbreviation for a distance type</returns> public static string Abbreviation(DistanceType distanceType) { return _shortAbbrev[(int)distanceType]; }
/// <summary> /// Parse a string. /// </summary> /// <param name="distance">String of valid numeric characters</param> /// <param name="distanceType">Distance type string represents (inches, miles, kilometers)</param> /// <returns>New DistanceSpan</returns> public static DistanceSpan Parse(string distance, DistanceType distanceType) { return new DistanceSpan(double.Parse(distance, CultureInfo.InvariantCulture), distanceType); }
private static extern IntPtr gpuBruteForceMatcherCreate(DistanceType distType);
public static double FromMetric(double meters, DistanceType outputType) { double _retval = 0D; switch (outputType) { case DistanceType.MileNautical: _retval = meters / GeoConstant.METERSINNMILE; break; case DistanceType.Mile: _retval = meters / GeoConstant.METERSINMILE; break; case DistanceType.Yard: _retval = meters / GeoConstant.METERSINYARD; break; case DistanceType.Inch: _retval = meters / GeoConstant.METERSININCH; break; case DistanceType.Foot: _retval = meters / GeoConstant.METERSINFOOT; break; case DistanceType.Kilometer: _retval = meters / 1000D; break; case DistanceType.Meter: _retval = meters; break; case DistanceType.Centimeter: _retval = meters * 100D; break; case DistanceType.Millimeter: _retval = meters * 1000D; break; default: throw new ArgumentException("DistanceType not supported"); } return _retval; }
/// <summary> /// Returns the full unit name (in English) for a particular distance span (kilometer, feet, mile) /// </summary> /// <param name="distance">Distance value to get name for</param> /// <param name="distanceType">Distance type to get name for</param> /// <returns>Lower case full name for a distance type</returns> public static string Name(DistanceSpan distance, DistanceType distanceType) { return (Math.Abs(distance._meters)<1)?_nameSingular[(int)distanceType]:_namePlural[(int)distanceType]; }
/// <summary> /// Convert a distance from one type to another /// </summary> /// <param name="value">Distance to convert</param> /// <param name="inputType">Type that value represents</param> /// <param name="outputType">Target type the return value represents</param> /// <returns>Converted distance that is of outputType</returns> public static double Convert(double value, DistanceSpan.DistanceType inputType, DistanceType outputType) { return FromMetric(ToMetric(value, inputType), outputType); }