public Model(string data_access,Form parent) { compute = new Compute(); data = new Data(data_access); FileInfo fi = new FileInfo(data_access); control = new Controller(parent, fi.Name.Replace(fi.Extension,""), this); //id = -1; }
/* Tests with Sqrt and Square */ public static void Main() { Compute test = new Compute(); ComputeDelegate compute = new ComputeDelegate(Math.Sqrt); Console.WriteLine(test.Test(5, compute)); compute = new ComputeDelegate(test.Square); Console.WriteLine(test.Test(5, compute)); Console.WriteLine(test.Test(5, (double x) => x*x*x)); }
public static Angle <T> operator +(Angle <T> left, Angle <T> right) { return(new Angle <T>(Compute <T> .Add(left._radians, right._radians))); }
public virtual bool Visit(Compute compute) { return(true); }
public async Task TestBuild() { // Read build entry. string treeURL = TestContext.DataRow["TreeURL"].ToString(); int level = Convert.ToInt32(TestContext.DataRow["Level"]); string buildFile = @"..\..\TestBuilds\" + TestContext.DataRow["BuildFile"].ToString(); List <string> expectDefense = new List <string>(); List <string> expectOffense = new List <string>(); if (TestContext.DataRow.Table.Columns.Contains("ExpectDefence")) { using (StringReader reader = new StringReader(TestContext.DataRow["ExpectDefence"].ToString())) { string line; while ((line = reader.ReadLine()) != null) { line = line.Trim(); if (line.Length > 0 && !line.StartsWith("#")) { expectDefense.Add(line.Trim()); } } } } if (TestContext.DataRow.Table.Columns.Contains("ExpectOffence")) { using (StringReader reader = new StringReader(TestContext.DataRow["ExpectOffence"].ToString())) { string line; while ((line = reader.ReadLine()) != null) { line = line.Trim(); if (line.Length > 0 && !line.StartsWith("#")) { expectOffense.Add(line.Trim()); } } } } var tree = await _treeTask; // Initialize structures. tree.LoadFromUrl(treeURL); tree.Level = level; string itemData = File.ReadAllText(buildFile); ItemAttributes itemAttributes = new ItemAttributes(new PersistentData(false), itemData); Compute.Initialize(tree, itemAttributes); // Compare defense properties. Dictionary <string, List <string> > defense = new Dictionary <string, List <string> >(); if (expectDefense.Count > 0) { foreach (ListGroup grp in Compute.Defense()) { List <string> props = new List <string>(); foreach (string item in grp.Properties.Select(InsertNumbersInAttributes)) { props.Add(item); } defense.Add(grp.Name, props); } List <string> group = null; foreach (string entry in expectDefense) { if (entry.Contains(':')) // Property: Value { Assert.IsNotNull(group, "Missing defence group [" + TestContext.DataRow["BuildFile"].ToString() + "]"); Assert.IsTrue(group.Contains(entry), "Wrong " + entry + " [" + TestContext.DataRow["BuildFile"].ToString() + "]"); } else // Group { Assert.IsTrue(defense.ContainsKey(entry), "No such defence group: " + entry + " [" + TestContext.DataRow["BuildFile"].ToString() + "]"); group = defense[entry]; } } } // Compare offense properties. Dictionary <string, List <string> > offense = new Dictionary <string, List <string> >(); if (expectOffense.Count > 0) { foreach (ListGroup grp in Compute.Offense()) { List <string> props = new List <string>(); foreach (string item in grp.Properties.Select(InsertNumbersInAttributes)) { props.Add(item); } offense.Add(grp.Name, props); } List <string> group = null; foreach (string entry in expectOffense) { if (entry.Contains(':')) // Property: Value { Assert.IsNotNull(group, "Missing offence group [" + TestContext.DataRow["BuildFile"].ToString() + "]"); Assert.IsTrue(group.Contains(entry), "Wrong " + entry + " [" + TestContext.DataRow["BuildFile"].ToString() + "]"); } else // Group { Assert.IsTrue(offense.ContainsKey(entry), "No such offence group: " + entry + " [" + TestContext.DataRow["BuildFile"].ToString() + "]"); group = offense[entry]; } } } }
protected override bool ShouldGenerateClass(Node node) { Compute compute = node as Compute; return(compute != null); }
internal static MachineLearningComputeData DeserializeMachineLearningComputeData(JsonElement element) { Optional <ManagedServiceIdentity> identity = default; Optional <string> location = default; Optional <IDictionary <string, string> > tags = default; Optional <MachineLearningSku> sku = default; Optional <Compute> properties = default; ResourceIdentifier id = default; string name = default; ResourceType type = default; SystemData systemData = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("identity")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } var serializeOptions = new JsonSerializerOptions { Converters = { new ManagedServiceIdentityTypeV3Converter() } }; identity = JsonSerializer.Deserialize <ManagedServiceIdentity>(property.Value.ToString(), serializeOptions); continue; } if (property.NameEquals("location")) { location = property.Value.GetString(); continue; } if (property.NameEquals("tags")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } Dictionary <string, string> dictionary = new Dictionary <string, string>(); foreach (var property0 in property.Value.EnumerateObject()) { dictionary.Add(property0.Name, property0.Value.GetString()); } tags = dictionary; continue; } if (property.NameEquals("sku")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } sku = MachineLearningSku.DeserializeMachineLearningSku(property.Value); continue; } if (property.NameEquals("properties")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } properties = Compute.DeserializeCompute(property.Value); continue; } if (property.NameEquals("id")) { id = new ResourceIdentifier(property.Value.GetString()); continue; } if (property.NameEquals("name")) { name = property.Value.GetString(); continue; } if (property.NameEquals("type")) { type = new ResourceType(property.Value.GetString()); continue; } if (property.NameEquals("systemData")) { systemData = JsonSerializer.Deserialize <SystemData>(property.Value.ToString()); continue; } } return(new MachineLearningComputeData(id, name, type, systemData, identity, location.Value, Optional.ToDictionary(tags), sku.Value, properties.Value)); }
public ProgramUI(IConsole consoleForAllReadsAndWrites) { _console = consoleForAllReadsAndWrites; Compute = new Compute(); }
/// <summary> /// Processes an override event for a machine into a project synchronously /// </summary> public override OverrideEventResponse Execute(OverrideEventRequestArgument arg) => Compute.Apply(func, arg);
private static bool InBox <T>(Vector <T> hit, Bounds <T> bounds, int axis) { if (bounds.Min.Dimensions != bounds.Max.Dimensions) { throw new Exception(); } int dimensions = bounds.Min.Dimensions; for (int i = 0; i < dimensions; i++) { if (axis == 1 && Compute.GreaterThan(hit[2], bounds.Min[2]) && Compute.LessThan(hit[2], bounds.Max[2]) && Compute.GreaterThan(hit[1], bounds.Min[1]) && Compute.LessThan(hit[1], bounds.Max[1])) { return(true); } } if (axis == 1 && Compute.GreaterThan(hit[2], bounds.Min[2]) && Compute.LessThan(hit[2], bounds.Max[2]) && Compute.GreaterThan(hit[1], bounds.Min[1]) && Compute.LessThan(hit[1], bounds.Max[1])) { return(true); } if (axis == 2 && Compute.GreaterThan(hit[2], bounds.Min[2]) && Compute.LessThan(hit[2], bounds.Max[2]) && Compute.GreaterThan(hit[0], bounds.Min[0]) && Compute.LessThan(hit[0], bounds.Max[0])) { return(true); } if (axis == 3 && Compute.GreaterThan(hit[0], bounds.Min[0]) && Compute.LessThan(hit[0], bounds.Max[0]) && Compute.GreaterThan(hit[1], bounds.Min[1]) && Compute.LessThan(hit[1], bounds.Max[1])) { return(true); } return(false); }
private static bool GetIntersection <T>(T fDst1, T fDst2, Bounds <T> bounds, out Vector <T> hit) { hit = null; if (Compute.GreaterThanOrEqual(Compute.Multiply(fDst1, fDst2), Constant <T> .Zero)) { return(false); } if (Compute.Equal(fDst1, fDst2)) { return(false); } hit = bounds.Min + (bounds.Max - bounds.Min) * Compute.Divide(Compute.Negate(fDst1), (Compute.Subtract(fDst2, fDst1))); return(true); }
/// <summary> /// Get the dictionary of intersections for the given stroke /// </summary> /// <param name="stroke"></param> /// <returns></returns> public Dictionary <string, int> GetIntersectionCounts(Substroke stroke) { if (!m_Stroke2Intersections.ContainsKey(stroke)) { throw new ArgumentException("The given stroke is not tracked by this intersection sketch"); } double avgArcLength = GetAvgArcLength(m_Sketch); double dA = Math.Min(avgArcLength, (stroke.SpatialLength + avgArcLength) / 2) * Compute.THRESHOLD; Dictionary <Substroke, Future <IntersectionPair> > intersections = m_Stroke2Intersections[stroke]; Dictionary <string, int> counts = new Dictionary <string, int>(4); counts.Add(NUM_LL_INTERSECTIONS, 0); counts.Add(NUM_LX_INTERSECTIONS, 0); counts.Add(NUM_XL_INTERSECTIONS, 0); counts.Add(NUM_XX_INTERSECTIONS, 0); foreach (Future <IntersectionPair> futurePair in intersections.Values) { IntersectionPair pair = futurePair.Value; double[] endDistances = new double[4]; endDistances[0] = Compute.EuclideanDistance(pair.StrokeA.Points[0], pair.StrokeB.Points[0]); endDistances[1] = Compute.EuclideanDistance(pair.StrokeA.Points[0], pair.StrokeB.Points[pair.StrokeB.Points.Length - 1]); endDistances[2] = Compute.EuclideanDistance(pair.StrokeA.Points[pair.StrokeA.Points.Length - 1], pair.StrokeB.Points[0]); endDistances[3] = Compute.EuclideanDistance(pair.StrokeA.Points[pair.StrokeA.Points.Length - 1], pair.StrokeB.Points[pair.StrokeB.Points.Length - 1]); Substroke otherStroke = pair.StrokeA; if (stroke == otherStroke) { otherStroke = pair.StrokeB; } double dB = Math.Min(avgArcLength, (otherStroke.SpatialLength + avgArcLength) / 2) * Compute.THRESHOLD; double d = Math.Min(dA, dB); if (pair.IsEmpty) { foreach (double dist in endDistances) { if (dist < d) { counts[NUM_LL_INTERSECTIONS]++; } } continue; } List <string> endIntersections = new List <string>(); foreach (Intersection intersection in pair.Intersections) { float a = intersection.GetIntersectionPoint(stroke); float b = intersection.GetOtherStrokesIntersectionPoint(stroke); if (a == -1.0f || b == -1.0f) { continue; } bool aL = false; bool bL = false; bool aL1 = false; bool aL2 = false; bool bL1 = false; bool bL2 = false; double d_over_A = dA / stroke.SpatialLength; double d_over_B = dB / otherStroke.SpatialLength; if (a < -d_over_A || a > (1.0 + d_over_A) || b < -d_over_B || b > (1.0 + d_over_B)) { continue; } if ((a <= d_over_A && a >= -d_over_A)) { aL1 = true; } else if ((a >= (1.0 - d_over_A) && (a <= 1.0 + d_over_A))) { aL2 = true; } if (aL1 || aL2) { aL = true; } if ((b <= d_over_B && b >= -d_over_B)) { bL1 = true; } else if ((b >= (1.0 - d_over_B) && (b <= 1.0 + d_over_B))) { bL2 = true; } if (bL1 || bL2) { bL = true; } string type; if (aL && bL) { type = "LL"; counts[NUM_LL_INTERSECTIONS]++; if (aL1 && bL1) { endIntersections.Add("a1b1"); } else if (aL1 && bL2) { endIntersections.Add("a1b2"); } else if (aL2 && bL1) { endIntersections.Add("a2b1"); } else if (aL2 && bL2) { endIntersections.Add("a2b2"); } } else if (aL) { type = "LX"; counts[NUM_LX_INTERSECTIONS]++; } else if (bL) { type = "XL"; counts[NUM_XL_INTERSECTIONS]++; } else { type = "XX"; counts[NUM_XX_INTERSECTIONS]++; } if (debug) { Console.WriteLine("{6}: a = {7}, dA = {0}, aInt = {2}, d/a = {4}, b = {8}, dB = {1}, bInt = {3}, d/b = {5}", dA.ToString("#0"), dB.ToString("#0"), a.ToString("#0.00"), b.ToString("#0.00"), d_over_A.ToString("#0.00"), d_over_B.ToString("#0.00"), type, stroke.SpatialLength.ToString("#0"), otherStroke.SpatialLength.ToString("#0")); } } if (endDistances[0] < d && !endIntersections.Contains("a1b1")) { counts[NUM_LL_INTERSECTIONS]++; } if (endDistances[1] < d && !endIntersections.Contains("a1b2")) { counts[NUM_LL_INTERSECTIONS]++; } if (endDistances[2] < d && !endIntersections.Contains("a2b1")) { counts[NUM_LL_INTERSECTIONS]++; } if (endDistances[3] < d && !endIntersections.Contains("a2b2")) { counts[NUM_LL_INTERSECTIONS]++; } } return(counts); }
private System.Drawing.RectangleF computeBoundingBox(Substroke substroke) { return(Compute.BoundingBox(m_Lines[substroke])); }
public UserNameController(ILogger <UserNameController> logger, Compute userNameCompute) { _logger = logger; _userNameCompute = userNameCompute; }
/// <summary> /// Processes an override event for a machine into a project asynchronously /// </summary> public override Task <OverrideEventResponse> ExecuteAsync(OverrideEventRequestArgument arg) => Compute.ApplyAsync(func, arg);
private void EvalExp(Compute compute, int stIdx, int edIdx) { int[] op = new int[] { -1, -1 }; while (expChr[stIdx] == '(' && expChr[edIdx - 1] == ')') { stIdx++; edIdx--; } for (int i = edIdx - 1; i >= stIdx; i--) { char c = expChr[i]; if (c == ')') { do { i--; } while (expChr[i] != '('); } else if (op[0] < 0 && (c == '*' || c == '/' || c == '%')) { op[0] = i; } else if (c == '+' || c == '-') { op[1] = i; break; } } if (op[1] < 0) { if (op[0] < 0) { EvalFloatValue(compute, stIdx, edIdx - stIdx, 1); } else { switch (expChr[op[0]]) { case '*': EvalExp(compute, stIdx, op[0]); EvalExp(compute, op[0] + 1, edIdx); compute.SetOperator(MULTIPLE); break; case '/': EvalExp(compute, stIdx, op[0]); EvalExp(compute, op[0] + 1, edIdx); compute.SetOperator(DIVISION); break; case '%': EvalExp(compute, stIdx, op[0]); EvalExp(compute, op[0] + 1, edIdx); compute.SetOperator(MODULO); break; } } } else { if (op[1] == stIdx) { switch (expChr[op[1]]) { case '-': EvalFloatValue(compute, stIdx + 1, edIdx - stIdx - 1, -1); break; case '+': EvalFloatValue(compute, stIdx + 1, edIdx - stIdx - 1, 1); break; } } else { switch (expChr[op[1]]) { case '+': EvalExp(compute, stIdx, op[1]); EvalExp(compute, op[1] + 1, edIdx); compute.SetOperator(PLUS); break; case '-': EvalExp(compute, stIdx, op[1]); EvalExp(compute, op[1] + 1, edIdx); compute.SetOperator(MINUS); break; } } } }
private static bool XenoDetection( XenoScan <T> a, XenoScan <T> b, int maxIterations, out Vector <T> point, out Vector <T> normal, out T penetration) { point = null; normal = null; penetration = default(T); Vector <T> minkowskiDifference = b.Position - a.Position; normal = -minkowskiDifference; if (NearlyZero(minkowskiDifference.MagnitudeSquared)) { minkowskiDifference = new Vector <T>( Compute.Divide(Constant <T> .One, Compute.FromInt32 <T>(100000)), Constant <T> .Zero, Constant <T> .Zero); } Vector <T> a_xenoScan1 = Quaternion <T> .Rotate(a.Orientation, a.XenoScan(Quaternion <T> .Rotate(a.Orientation, minkowskiDifference))); Vector <T> b_xenoScan1 = Quaternion <T> .Rotate(b.Orientation, b.XenoScan(Quaternion <T> .Rotate(b.Orientation, normal))); Vector <T> xenoScans1_subtract = b_xenoScan1 - a_xenoScan1; if (Compute.LessThanOrEqual(Vector <T> .DotProduct(xenoScans1_subtract, normal), Constant <T> .Zero)) { return(false); } Vector <T> crossOfXenoAndMD = Vector <T> .CrossProduct(xenoScans1_subtract, minkowskiDifference); if (NearlyZero(crossOfXenoAndMD.MagnitudeSquared)) { crossOfXenoAndMD = (xenoScans1_subtract - minkowskiDifference).Normalize(); point = (a_xenoScan1 + b_xenoScan1) * Compute.Divide(Constant <T> .One, Constant <T> .Two); penetration = Vector <T> .DotProduct(xenoScans1_subtract, crossOfXenoAndMD); return(true); } Vector <T> a_xenoScan2 = Quaternion <T> .Rotate(a.Orientation, a.XenoScan(Quaternion <T> .Rotate(a.Orientation, -crossOfXenoAndMD))); Vector <T> b_xenoScan2 = Quaternion <T> .Rotate(b.Orientation, b.XenoScan(Quaternion <T> .Rotate(b.Orientation, normal))); Vector <T> xenoScans2_subtract = b_xenoScan2 - a_xenoScan2; if (Compute.LessThanOrEqual(Vector <T> .DotProduct(xenoScans2_subtract, normal), Constant <T> .Zero)) { return(false); } Vector <T> crossOfXenoScans = Vector <T> .CrossProduct(xenoScans1_subtract - minkowskiDifference, xenoScans2_subtract - minkowskiDifference); T distance = Vector <T> .DotProduct(crossOfXenoAndMD, minkowskiDifference); if (Compute.LessThan(distance, Constant <T> .Zero)) { Vector <T> temp; temp = xenoScans1_subtract; xenoScans1_subtract = xenoScans2_subtract; xenoScans2_subtract = temp; temp = a_xenoScan1; a_xenoScan1 = a_xenoScan2; a_xenoScan2 = temp; temp = b_xenoScan1; b_xenoScan1 = b_xenoScan2; b_xenoScan2 = temp; normal = -normal; } int phase2 = 0; int phase1 = 0; bool hit = false; while (true) { if (phase1 > maxIterations) { return(false); } phase1++; Vector <T> neg_normal = -normal; Vector <T> a_xenoScan3 = Quaternion <T> .Rotate(a.Orientation, a.XenoScan(Quaternion <T> .Rotate(a.Orientation, neg_normal))); Vector <T> b_xenoScan3 = Quaternion <T> .Rotate(b.Orientation, b.XenoScan(Quaternion <T> .Rotate(b.Orientation, normal))); Vector <T> xenoScans3_subtract = b_xenoScan3 - a_xenoScan3; if (Compute.LessThan(Vector <T> .DotProduct(xenoScans3_subtract, normal), Constant <T> .Zero)) { return(false); } if (Compute.LessThan(Vector <T> .DotProduct(Vector <T> .CrossProduct(xenoScans1_subtract, xenoScans3_subtract), minkowskiDifference), Constant <T> .Zero)) { xenoScans2_subtract = xenoScans3_subtract; a_xenoScan2 = a_xenoScan3; b_xenoScan2 = b_xenoScan3; normal = Vector <T> .CrossProduct(xenoScans1_subtract - minkowskiDifference, xenoScans3_subtract - minkowskiDifference); continue; } if (Compute.LessThan(Vector <T> .DotProduct(Vector <T> .CrossProduct(xenoScans3_subtract, xenoScans2_subtract), minkowskiDifference), Constant <T> .Zero)) { xenoScans1_subtract = xenoScans3_subtract; a_xenoScan1 = a_xenoScan3; b_xenoScan1 = b_xenoScan3; normal = Vector <T> .CrossProduct(xenoScans3_subtract - minkowskiDifference, xenoScans2_subtract - minkowskiDifference); continue; } while (true) { phase2++; normal = Vector <T> .CrossProduct(xenoScans2_subtract - xenoScans1_subtract, xenoScans3_subtract - xenoScans1_subtract); // Ommited because appears to be an error //if (NearlyZero(normal.Magnitude())) // return true; normal = normal.Normalize(); if (!hit && Compute.GreaterThanOrEqual(Vector <T> .DotProduct(normal, xenoScans1_subtract), Constant <T> .Zero)) { hit = true; } neg_normal = -normal; Vector <T> a_xenoScan4 = Quaternion <T> .Rotate(a.Orientation, a.XenoScan(Quaternion <T> .Rotate(a.Orientation, neg_normal))); Vector <T> b_xenoScan4 = Quaternion <T> .Rotate(b.Orientation, b.XenoScan(Quaternion <T> .Rotate(b.Orientation, normal))); Vector <T> xenoScans4_subtract = b_xenoScan4 - a_xenoScan4; T delta = Vector <T> .DotProduct(xenoScans4_subtract - xenoScans3_subtract, normal); penetration = Vector <T> .DotProduct(xenoScans4_subtract, normal); // If the boundary is thin enough or the origin is outside the support plane for the newly discovered vertex, then we can terminate if (Compute.LessThanOrEqual(delta, CollideEpsilon) || Compute.LessThanOrEqual(penetration, Constant <T> .Zero) || phase2 > maxIterations) { if (hit) { T b0 = Vector <T> .DotProduct(Vector <T> .CrossProduct(xenoScans1_subtract, xenoScans2_subtract), xenoScans3_subtract); T b1 = Vector <T> .DotProduct(Vector <T> .CrossProduct(xenoScans3_subtract, xenoScans2_subtract), minkowskiDifference); T b2 = Vector <T> .DotProduct(Vector <T> .CrossProduct(minkowskiDifference, xenoScans1_subtract), xenoScans3_subtract); T b3 = Vector <T> .DotProduct(Vector <T> .CrossProduct(xenoScans2_subtract, xenoScans1_subtract), minkowskiDifference); T sum = Compute.Add(b0, b1, b2, b3); if (Compute.LessThanOrEqual(sum, Constant <T> .Zero)) { b0 = Constant <T> .Zero; b1 = Vector <T> .DotProduct(Vector <T> .CrossProduct(xenoScans2_subtract, xenoScans3_subtract), normal); b2 = Vector <T> .DotProduct(Vector <T> .CrossProduct(xenoScans3_subtract, xenoScans1_subtract), normal); b3 = Vector <T> .DotProduct(Vector <T> .CrossProduct(xenoScans1_subtract, xenoScans2_subtract), normal); sum = Compute.Add(b0, b1, b2, b3); } T inv = Compute.Divide(Constant <T> .One, sum); point = (a.Position * b0 + a_xenoScan1 * b1 + a_xenoScan2 * b2 + a_xenoScan3 * b3 + b.Position * b0 + b_xenoScan1 * b1 + b_xenoScan2 * b2 + b_xenoScan3 * b3) * inv; } return(hit); } Vector <T> xeno4CrossMD = Vector <T> .CrossProduct(xenoScans4_subtract, minkowskiDifference); T dot = Vector <T> .DotProduct(xeno4CrossMD, xenoScans1_subtract); if (Compute.GreaterThanOrEqual(dot, Constant <T> .Zero)) { dot = Vector <T> .DotProduct(xeno4CrossMD, xenoScans2_subtract); if (Compute.GreaterThanOrEqual(dot, Constant <T> .Zero)) { xenoScans1_subtract = xenoScans4_subtract; a_xenoScan1 = a_xenoScan4; b_xenoScan1 = b_xenoScan4; } else { xenoScans3_subtract = xenoScans4_subtract; a_xenoScan3 = a_xenoScan4; b_xenoScan3 = b_xenoScan4; } } else { dot = Vector <T> .DotProduct(xeno4CrossMD, xenoScans3_subtract); if (Compute.GreaterThanOrEqual(dot, Constant <T> .Zero)) { xenoScans2_subtract = xenoScans4_subtract; a_xenoScan2 = a_xenoScan4; b_xenoScan2 = b_xenoScan4; } else { xenoScans1_subtract = xenoScans4_subtract; a_xenoScan1 = a_xenoScan4; b_xenoScan1 = b_xenoScan4; } } } } }
public static void TestOmnitree1() { #region construction Omnitree.Locate <TestObject, double> locate = (TestObject record) => { return((int i) => { switch (i) { case 0: return record.X; case 1: return record.Y; case 2: return record.Z; default: throw new System.Exception(); } }); }; Compute <double> .Compare(0, 0); Omnitree <TestObject, double> omnitree = new OmnitreeLinked <TestObject, double>( new double[] { 0, 0, 0 }, new double[] { 1, 1, 1 }, locate, Compute <double> .Compare, (double a, double b) => { return((a + b) / 2); }); #endregion #region random generation Console.WriteLine("Generating random data..."); Random random = new Random(0); int count = 100; TestObject[] records = new TestObject[count]; for (int i = 0; i < count; i++) { records[i] = new TestObject(i, random.NextDouble(), random.NextDouble(), random.NextDouble()); } Console.WriteLine("Generated random data."); #endregion #region adding Console.WriteLine("Building Omnitree..."); for (int i = 0; i < count; i++) { omnitree.Add(records[i]); if (i % (count / 10) == 0) { Console.WriteLine(((double)i / (double)count * 100D) + "%"); } } Console.WriteLine("OmniTree.Count: " + omnitree.Count); //Console.WriteLine("OmniTree._top.Count: " + (omnitree as OmnitreeLinked<TestObject, double>)._top.Count); int test_count = 0; omnitree.Stepper((TestObject record) => { test_count++; }); Console.WriteLine("OmniTree Stepper Count: " + test_count); #endregion #region validation SetHashArray <TestObject> setHash = new SetHashArray <TestObject>( (TestObject a, TestObject b) => { return(a.Id == b.Id); }, (TestObject a) => { return(a.Id.GetHashCode()); }); for (int i = 0; i < count; i++) { setHash.Add(records[i]); } bool validated = true; omnitree.Stepper((TestObject record) => { if (!setHash.Contains(record)) { validated = false; } }); if (validated) { Console.WriteLine("Values Validated."); } else { Console.WriteLine("Values INVALID."); } #endregion #region querying Console.WriteLine("Value Querying: "); bool query_test = false; for (int i = 0; i < count; i++) { query_test = false; omnitree[locate(records[i])]((TestObject record) => { query_test = true; }); if (query_test == false) { Console.WriteLine("Querying INVALID on value: " + i); break; } if (i % (count / 10) == 0) { Console.WriteLine(((double)i / (double)count * 100D) + "%"); } } if (query_test == true) { Console.WriteLine("Querying Validated."); } else { Console.WriteLine("Querying INVALID."); } #endregion #region dynamic values (re-randomizing) Console.WriteLine("Moving randomized data..."); foreach (TestObject record in records) { record.X += Math.Max(0d, Math.Min(1d, (random.NextDouble() / 100D) - .5D)); record.Y += Math.Max(0d, Math.Min(1d, (random.NextDouble() / 100D) - .5D)); record.Z += Math.Max(0d, Math.Min(1d, (random.NextDouble() / 100D) - .5D)); } Console.WriteLine("Randomized data moved."); #endregion #region Updating Console.WriteLine("Updating Tree Positions..."); //// Update Method #1 omnitree.Update(); //// Update Method #2 //omnitree.Update(omnitree.Min, omnitree.Max); Console.WriteLine("Tree Positions Updated."); #endregion #region removal Console.WriteLine("Removing Values: "); for (int i = 0; i < count; i++) { //// Removal Method #1 omnitree.Remove(records[i]); //// Removal Method #2 //omnitree.Remove(locate(records[i]), locate(records[i])); //// Removal Method #3 //omnitree.Remove(locate(records[i]), locate(records[i]), (omnitree_record step) => { return records[i].Id == step.Id; }); //// Removal Method #4 //double[] location = new double[] { locate(records[i])(0), locate(records[i])(1), locate(records[i])(2) }; //omnitree.Remove(location, location); //// Removal Method #5 //double[] location = new double[] { locate(records[i])(0), locate(records[i])(1), locate(records[i])(2) }; //omnitree.Remove(location, location, (omnitree_record step) => { return records[i].Id == step.Id; }); if (omnitree.Count != count - (i + 1)) { throw new System.Exception(); } if (i % (count / 10) == 0) { Console.WriteLine(((double)i / (double)count * 100D) + "%"); } } Console.WriteLine("Values Removed: "); Console.WriteLine("OmniTree.Count: " + omnitree.Count); //Console.WriteLine("OmniTree._top.Count: " + (omnitree as OmnitreeLinked<TestObject, double>)._top.Count); test_count = 0; omnitree.Stepper((TestObject record) => { test_count++; }); Console.WriteLine("OmniTree Stepper Count: " + test_count); #endregion Console.WriteLine(); Console.WriteLine("TEST COMPLETE"); }
protected override void GenerateMethod(Node node, StreamWriter stream, string indent) { base.GenerateMethod(node, stream, indent); Compute compute = node as Compute; Debug.Check(compute != null); stream.WriteLine("{0}\t\tvirtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)", indent); stream.WriteLine("{0}\t\t{{", indent); stream.WriteLine("{0}\t\t\tBEHAVIAC_UNUSED_VAR(pAgent);", indent); stream.WriteLine("{0}\t\t\tBEHAVIAC_UNUSED_VAR(childStatus);", indent); stream.WriteLine("{0}\t\t\tEBTStatus result = BT_SUCCESS;", indent); if (compute.Opl != null && compute.Opr1 != null && compute.Opr2 != null) { RightValueCppExporter.GenerateCode(compute.Opr1, stream, indent + "\t\t\t", compute.Opr1.NativeType, "opr1", "opr1"); RightValueCppExporter.GenerateCode(compute.Opr2, stream, indent + "\t\t\t", compute.Opr2.NativeType, "opr2", "opr2"); string oprStr = string.Empty; switch (compute.Operator) { case ComputeOperator.Add: oprStr = "opr1 + opr2"; break; case ComputeOperator.Sub: oprStr = "opr1 - opr2"; break; case ComputeOperator.Mul: oprStr = "opr1 * opr2"; break; case ComputeOperator.Div: oprStr = "opr1 / opr2"; break; default: Debug.Check(false, "The operator is wrong!"); break; } string basicType = DataCppExporter.GetBasicGeneratedNativeType(compute.Opl.NativeType); stream.WriteLine("{0}\t\t\t{1} opr = ({1})({2});", indent, basicType, oprStr); if (compute.Opl.IsPar) { ParInfo par = compute.Opl.Value as ParInfo; if (par != null) { uint id = Behaviac.Design.CRC32.CalcCRC(par.Name); stream.WriteLine("{0}\t\t\tBEHAVIAC_ASSERT(behaviac::MakeVariableId(\"{1}\") == {2}u);", indent, par.Name, id); stream.WriteLine("{0}\t\t\tpAgent->SetVariable(\"{1}\", opr, {2}u);", indent, par.Name, id); } } else { string opl = VariableCppExporter.GenerateCode(compute.Opl, stream, indent + "\t\t\t", string.Empty, string.Empty, "opl"); stream.WriteLine("{0}\t\t\t{1} = opr;", indent, opl); VariableCppExporter.PostGenerateCode(compute.Opl, stream, indent + "\t\t\t", compute.Opl.NativeType, "opl", string.Empty, null, "", "opr"); } if (compute.Opr1.IsMethod) { RightValueCppExporter.PostGenerateCode(compute.Opr1, stream, indent + "\t\t\t", compute.Opr1.NativeType, "opr1", string.Empty); } if (compute.Opr2.IsMethod) { RightValueCppExporter.PostGenerateCode(compute.Opr2, stream, indent + "\t\t\t", compute.Opr2.NativeType, "opr2", string.Empty); } } stream.WriteLine("{0}\t\t\treturn result;", indent); stream.WriteLine("{0}\t\t}}", indent); }
static void Main(string[] args) { Random random = new Random(); int test = 10; Console.WriteLine("You are runnning the Data Structures example."); Console.WriteLine("======================================================"); Console.WriteLine(); #region Link (aka Tuple) Console.WriteLine(" Link------------------------------------"); Console.WriteLine(); Console.WriteLine(" A \"Link\" is like a System.Tuple that implements"); Console.WriteLine(" Towel.DataStructures.DataStructure. A Link/Tuple is"); Console.WriteLine(" used when you have a small, known-sized set of objects"); Console.WriteLine(" that you want to bundle together without making a custom"); Console.WriteLine(" custom class."); Console.WriteLine(); Link link = new Link <int, int, int, int, int, int>(0, 1, 2, 3, 4, 5); Console.Write(" Traversal: "); link.Stepper(i => Console.Write(i)); Console.WriteLine(); Console.WriteLine(" Size: " + link.Size); Console.WriteLine(); #endregion #region Array Console.WriteLine(" Array---------------------------------"); Console.WriteLine(); Console.WriteLine(" An Array<T> is just a wrapper for arrays that implements"); Console.WriteLine(" Towel.DataStructures.DataStructure. An array is used when"); Console.WriteLine(" dealing with static-sized, known-sized sets of data. Arrays"); Console.WriteLine(" can be sorted along 1 dimensions for binary searching algorithms."); Console.WriteLine(); IArray <int> indexed = new Array <int>(test); Console.Write(" Filling in (0-" + (test - 1) + ")..."); for (int i = 0; i < test; i++) { indexed[i] = i; } Console.WriteLine(); Console.Write(" Traversal: "); indexed.Stepper(i => Console.Write(i)); Console.WriteLine(); Console.WriteLine(" Length: " + indexed.Length); Console.WriteLine(); #endregion #region List Console.WriteLine(" List---------------------------------"); Console.WriteLine(); Console.WriteLine(" An List is like an IList that implements"); Console.WriteLine(" Towel.DataStructures.DataStructure. \"ListArray\" is"); Console.WriteLine(" the array implementation while \"ListLinked\" is the"); Console.WriteLine(" the linked-list implementation. An List is used"); Console.WriteLine(" when dealing with an unknown quantity of data that you"); Console.WriteLine(" will likely have to enumerate/step through everything. The"); Console.WriteLine(" ListArray shares the properties of an Array in"); Console.WriteLine(" that it can be relateively quickly sorted along 1 dimensions"); Console.WriteLine(" for binary search algorithms."); Console.WriteLine(); // ListArray --------------------------------------- IList <int> addableArray = new ListArray <int>(test); Console.Write(" [ListArray] Adding (0-" + (test - 1) + ")..."); for (int i = 0; i < test; i++) { addableArray.Add(i); } Console.WriteLine(); Console.Write(" [ListArray] Traversal: "); addableArray.Stepper(i => Console.Write(i)); Console.WriteLine(); Console.WriteLine(" [ListArray] Count: " + addableArray.Count); addableArray.Clear(); // Clears the addable Console.WriteLine(); // ListLinked --------------------------------------- IList <int> addableLinked = new ListLinked <int>(); Console.Write(" [ListLinked] Adding (0-" + (test - 1) + ")..."); for (int i = 0; i < test; i++) { addableLinked.Add(i); } Console.WriteLine(); Console.Write(" [ListLinked] Traversal: "); addableLinked.Stepper(i => Console.Write(i)); Console.WriteLine(); Console.WriteLine(" [ListLinked] Count: " + addableLinked.Count); addableLinked.Clear(); // Clears the addable Console.WriteLine(); #endregion #region Stack { Console.WriteLine(" Stack---------------------------------"); Console.WriteLine(); Console.WriteLine(" An \"Stack\" is a Stack that implements"); Console.WriteLine(" Towel.DataStructures.DataStructure. \"StackArray\" is"); Console.WriteLine(" the array implementation while \"StackLinked\" is the"); Console.WriteLine(" the linked-list implementation. A Stack is used"); Console.WriteLine(" specifically when you need the algorithm provided by the Push"); Console.WriteLine(" and Pop functions."); Console.WriteLine(); IStack <int> firstInLastOutArray = new StackArray <int>(); Console.Write(" [StackArray] Pushing (0-" + (test - 1) + ")..."); for (int i = 0; i < test; i++) { firstInLastOutArray.Push(i); } Console.WriteLine(); Console.Write(" [StackArray] Traversal: "); firstInLastOutArray.Stepper(i => Console.Write(i)); Console.WriteLine(); Console.WriteLine(" [StackArray] Pop: " + firstInLastOutArray.Pop()); Console.WriteLine(" [StackArray] Pop: " + firstInLastOutArray.Pop()); Console.WriteLine(" [StackArray] Peek: " + firstInLastOutArray.Peek()); Console.WriteLine(" [StackArray] Pop: " + firstInLastOutArray.Pop()); Console.WriteLine(" [StackArray] Count: " + firstInLastOutArray.Count); firstInLastOutArray.Clear(); // Clears the firstInLastOut Console.WriteLine(); IStack <int> firstInLastOutLinked = new StackLinked <int>(); Console.Write(" [StackLinked] Pushing (0-" + (test - 1) + ")..."); for (int i = 0; i < test; i++) { firstInLastOutLinked.Push(i); } Console.WriteLine(); Console.Write(" [StackLinked] Traversal: "); firstInLastOutLinked.Stepper(i => Console.Write(i)); Console.WriteLine(); Console.WriteLine(" [StackLinked] Pop: " + firstInLastOutLinked.Pop()); Console.WriteLine(" [StackLinked] Pop: " + firstInLastOutLinked.Pop()); Console.WriteLine(" [StackLinked] Peek: " + firstInLastOutLinked.Peek()); Console.WriteLine(" [StackLinked] Pop: " + firstInLastOutLinked.Pop()); Console.WriteLine(" [StackLinked] Count: " + firstInLastOutLinked.Count); firstInLastOutLinked.Clear(); // Clears the firstInLastOut Console.WriteLine(); } #endregion #region Queue { Console.WriteLine(" Queue---------------------------------"); Console.WriteLine(); Console.WriteLine(" An \"Queue\" is a Queue that implements"); Console.WriteLine(" Towel.DataStructures.DataStructure. \"QueueArray\" is"); Console.WriteLine(" the array implementation while \"QueueLinked\" is the"); Console.WriteLine(" the linked-list implementation. A Queue/Stack is used"); Console.WriteLine(" specifically when you need the algorithm provided by the Queue"); Console.WriteLine(" and Dequeue functions."); Console.WriteLine(); IQueue <int> firstInFirstOutArray = new QueueArray <int>(); Console.Write(" [QueueArray] Enqueuing (0-" + (test - 1) + ")..."); for (int i = 0; i < test; i++) { firstInFirstOutArray.Enqueue(i); } Console.WriteLine(); Console.Write(" [QueueArray] Traversal: "); firstInFirstOutArray.Stepper(i => Console.Write(i)); Console.WriteLine(); Console.WriteLine(" [QueueArray] Dequeue: " + firstInFirstOutArray.Dequeue()); Console.WriteLine(" [QueueArray] Dequeue: " + firstInFirstOutArray.Dequeue()); Console.WriteLine(" [QueueArray] Peek: " + firstInFirstOutArray.Peek()); Console.WriteLine(" [QueueArray] Dequeue: " + firstInFirstOutArray.Dequeue()); Console.WriteLine(" [QueueArray] Count: " + firstInFirstOutArray.Count); firstInFirstOutArray.Clear(); // Clears the firstInLastOut Console.WriteLine(); IQueue <int> firstInFirstOutLinked = new QueueLinked <int>(); Console.Write(" [QueueLinked] Enqueuing (0-" + (test - 1) + ")..."); for (int i = 0; i < test; i++) { firstInFirstOutLinked.Enqueue(i); } Console.WriteLine(); Console.Write(" [QueueLinked] Traversal: "); firstInFirstOutLinked.Stepper(i => Console.Write(i)); Console.WriteLine(); Console.WriteLine(" [QueueLinked] Pop: " + firstInFirstOutLinked.Dequeue()); Console.WriteLine(" [QueueLinked] Pop: " + firstInFirstOutLinked.Dequeue()); Console.WriteLine(" [QueueLinked] Peek: " + firstInFirstOutLinked.Peek()); Console.WriteLine(" [QueueLinked] Pop: " + firstInFirstOutLinked.Dequeue()); Console.WriteLine(" [QueueLinked] Count: " + firstInFirstOutLinked.Count); firstInFirstOutLinked.Clear(); // Clears the firstInLastOut Console.WriteLine(); } #endregion #region Heap { Console.WriteLine(" Heap---------------------------------"); Console.WriteLine(); Console.WriteLine(" An \"Heap\" is a binary tree that stores items based on priorities."); Console.WriteLine(" It implements Towel.DataStructures.DataStructure like the others."); Console.WriteLine(" It uses sifting algorithms to move nodes vertically through itself."); Console.WriteLine(" It is often the best data structure for standard priority queues."); Console.WriteLine(" \"HeapArray\" is an implementation where the tree has been flattened"); Console.WriteLine(" into an array."); Console.WriteLine(); Console.WriteLine(" Let's say the priority is how close a number is to \"5\"."); Console.WriteLine(" So \"Dequeue\" will give us the next closest value to \"5\"."); CompareResult Priority(int a, int b) { int _a = Compute.AbsoluteValue(a - 5); int _b = Compute.AbsoluteValue(b - 5); CompareResult comparison = Compare.Wrap(_b.CompareTo(_a)); return(comparison); } Console.WriteLine(); IHeap <int> heapArray = new HeapArray <int>(Priority); Console.Write(" [HeapArray] Enqueuing (0-" + (test - 1) + ")..."); for (int i = 0; i < test; i++) { heapArray.Enqueue(i); } Console.WriteLine(); Console.WriteLine(" [HeapArray] Dequeue: " + heapArray.Dequeue()); Console.WriteLine(" [HeapArray] Dequeue: " + heapArray.Dequeue()); Console.WriteLine(" [HeapArray] Peek: " + heapArray.Peek()); Console.WriteLine(" [HeapArray] Dequeue: " + heapArray.Dequeue()); Console.WriteLine(" [HeapArray] Count: " + heapArray.Count); heapArray.Clear(); // Clears the heapArray Console.WriteLine(); } #endregion #region Tree //Console.WriteLine(" Tree-----------------------------"); //Tree<int> tree_Map = new TreeMap<int>(0, Compute.Equal, Hash.Default); //for (int i = 1; i < test; i++) //{ // tree_Map.Add(i, i / Compute.SquareRoot(i)); //} //Console.Write(" Children of 0 (root): "); //tree_Map.Children(0, (int i) => { Console.Write(i + " "); }); //Console.WriteLine(); //Console.Write(" Children of " + ((int)System.Math.Sqrt(test) - 1) + " (root): "); //tree_Map.Children(((int)System.Math.Sqrt(test) - 1), (int i) => { Console.Write(i + " "); }); //Console.WriteLine(); //Console.Write(" Traversal: "); //tree_Map.Stepper((int i) => { Console.Write(i + " "); }); //Console.WriteLine(); //Console.WriteLine(); #endregion #region AVL Tree { Console.WriteLine(" AvlTree------------------------------------------------"); Console.WriteLine(); Console.WriteLine(" An AVL Tree is a sorted binary tree."); Console.WriteLine(" It implements Towel.DataStructures.DataStructure like the others."); Console.WriteLine(" It allows for very fast 1D ranged queries/traversals."); Console.WriteLine(" It is very similar to an Red Black tree, but uses a different sorting algorithm."); Console.WriteLine(); IAvlTree <int> avlTree = new AvlTreeLinked <int>(); Console.Write(" Adding (0-" + (test - 1) + ")..."); for (int i = 0; i < test; i++) { avlTree.Add(i); } Console.WriteLine(); Console.Write(" Traversal: "); avlTree.Stepper(i => Console.Write(i)); Console.WriteLine(); //// Note: Because the nodes in AVL Tree linked do not have //// a parent pointer, the IEnumerable "foreach" iteration //// is extremely slow and should be avoided. It requires //// a stack for it's iteration. // //Console.Write(" Traversal Foreach: "); //foreach (int i in avlTree) //{ // Console.Write(i); //} //Console.WriteLine(); int minimum = random.Next(1, test / 2); int maximum = random.Next(1, test / 2) + test / 2; Console.Write(" Ranged Traversal [" + minimum + "-" + maximum + "]: "); avlTree.Stepper(i => Console.Write(i), minimum, maximum); Console.WriteLine(); int removal = random.Next(0, test); Console.Write(" Remove(" + removal + "): "); avlTree.Remove(removal); avlTree.Stepper(i => Console.Write(i)); Console.WriteLine(); int contains = random.Next(0, test); Console.WriteLine(" Contains(" + contains + "): " + avlTree.Contains(contains)); Console.WriteLine(" Current Least: " + avlTree.CurrentLeast); Console.WriteLine(" Current Greatest: " + avlTree.CurrentGreatest); Console.WriteLine(" Count: " + avlTree.Count); avlTree.Clear(); // Clears the AVL tree Console.WriteLine(); } #endregion #region Red-Black Tree { Console.WriteLine(" Red-Black Tree------------------------------------------------"); Console.WriteLine(); Console.WriteLine(" An Red-Black Tree is a sorted binary tree."); Console.WriteLine(" It implements Towel.DataStructures.DataStructure like the others."); Console.WriteLine(" It allows for very fast 1D ranged queries/traversals."); Console.WriteLine(" It is very similar to an AVL tree, but uses a different sorting algorithm."); Console.WriteLine(); IRedBlackTree <int> redBlackTree = new RedBlackTreeLinked <int>(); Console.Write(" Adding (0-" + (test - 1) + ")..."); for (int i = 0; i < test; i++) { redBlackTree.Add(i); } Console.WriteLine(); Console.Write(" Traversal: "); redBlackTree.Stepper(i => Console.Write(i)); Console.WriteLine(); int minimum = random.Next(1, test / 2); int maximum = random.Next(1, test / 2) + test / 2; Console.Write(" Ranged Traversal [" + minimum + "-" + maximum + "]: "); redBlackTree.Stepper(i => Console.Write(i), minimum, maximum); Console.WriteLine(); int removal = random.Next(0, test); Console.Write(" Remove(" + removal + "): "); redBlackTree.Remove(removal); redBlackTree.Stepper(i => Console.Write(i)); Console.WriteLine(); int contains = random.Next(0, test); Console.WriteLine(" Contains(" + contains + "): " + redBlackTree.Contains(contains)); Console.WriteLine(" Current Least: " + redBlackTree.CurrentLeast); Console.WriteLine(" Current Greatest: " + redBlackTree.CurrentGreatest); Console.WriteLine(" Count: " + redBlackTree.Count); redBlackTree.Clear(); // Clears the Red Black tree Console.WriteLine(); } #endregion #region BTree { Console.WriteLine(" B Tree------------------------------------------------"); Console.WriteLine(); Console.WriteLine(" A B Tree is a sorted binary tree that allows multiple values to"); Console.WriteLine(" be stored per node. This makes it sort of a hybrid between a"); Console.WriteLine(" binary tree and an array. Because multiple values are stored "); Console.WriteLine(" per node, it means less nodes must be traversed to completely"); Console.WriteLine(" traverse the values in the B tree."); Console.WriteLine(); Console.WriteLine(" The generic B Tree in Towel is still in development."); Console.WriteLine(); } #endregion #region Set { Console.WriteLine(" Set------------------------------------------------"); Console.WriteLine(); Console.WriteLine(" A Set is like an List, but it does not allow duplicates. Sets are"); Console.WriteLine(" usually implemented using hash codes. Implementations with hash codes"); Console.WriteLine(" usually have very fast \"Contains\" checks to see if a value has already"); Console.WriteLine(" been added to the set."); Console.WriteLine(); ISet <int> setHashLinked = new SetHashLinked <int>(); Console.Write(" Adding (0-" + (test - 1) + ")..."); for (int i = 0; i < test; i++) { setHashLinked.Add(i); } Console.WriteLine(); Console.Write(" Traversal: "); setHashLinked.Stepper(i => Console.Write(i)); Console.WriteLine(); int a = random.Next(0, test); setHashLinked.Remove(a); Console.Write(" Remove(" + a + "): "); setHashLinked.Stepper(i => Console.Write(i)); Console.WriteLine(); int b = random.Next(0, test); Console.WriteLine(" Contains(" + b + "): " + setHashLinked.Contains(b)); Console.WriteLine(" Count: " + setHashLinked.Count); Console.WriteLine(); } #endregion #region Map (aka Dictionary) { Console.WriteLine(" Map------------------------------------------------"); Console.WriteLine(); Console.WriteLine(" A Map (aka Dictionary) is similar to a Set, but it stores two values (a "); Console.WriteLine(" key and a value). Maps do not allow duplicate keys much like Sets don't"); Console.WriteLine(" allow duplicate values. When provided with the key, the Map uses that key"); Console.WriteLine(" to look up the value that it is associated with. Thus, it allows you to "); Console.WriteLine(" \"map\" one object to another. As with Sets, Maps are usually implemented"); Console.WriteLine(" using hash codes."); Console.WriteLine(); // Note: the first generic is the value, the second is the key IMap <string, int> mapHashLinked = new MapHashLinked <string, int>(); Console.WriteLine(" Let's map each int to its word representation (ex 1 -> One)."); Console.Write(" Adding (0-" + (test - 1) + ")..."); for (int i = 0; i < test; i++) { mapHashLinked.Add(i, ((decimal)i).ToEnglishWords()); } Console.WriteLine(); Console.WriteLine(" Traversal: "); mapHashLinked.Keys(i => Console.WriteLine(" " + i + "->" + mapHashLinked[i])); Console.WriteLine(); int a = random.Next(0, test); mapHashLinked.Remove(a); Console.Write(" Remove(" + a + "): "); mapHashLinked.Keys(i => Console.Write(i)); Console.WriteLine(); int b = random.Next(0, test); Console.WriteLine(" Contains(" + b + "): " + mapHashLinked.Contains(b)); Console.WriteLine(" Count: " + mapHashLinked.Count); Console.WriteLine(); } #endregion #region OmnitreePoints { Console.WriteLine(" OmnitreePoints--------------------------------------"); Console.WriteLine(); Console.WriteLine(" An Omnitree is an ND SPT that allows for"); Console.WriteLine(" multidimensional sorting. Any time you need to look"); Console.WriteLine(" items up based on multiple fields/properties, then"); Console.WriteLine(" you might want to use an Omnitree. If you need to"); Console.WriteLine(" perform ranged queries on multiple dimensions, then"); Console.WriteLine(" the Omnitree is the data structure for you."); Console.WriteLine(); Console.WriteLine(" The \"OmnitreePoints\" stores individual points (vectors),"); Console.WriteLine(" and the \"OmnitreeBounds\" stores bounded objects (spaces)."); Console.WriteLine(); IOmnitreePoints <int, double, string, decimal> omnitree = new OmnitreePointsLinked <int, double, string, decimal>( // This is a location delegate. (how to locate the item along each dimension) (int index, out double a, out string b, out decimal c) => { a = index; b = index.ToString(); c = index; }); Console.Write(" Adding (0-" + (test - 1) + ")..."); for (int i = 0; i < test; i++) { omnitree.Add(i); } Console.WriteLine(); Console.Write(" Traversal: "); omnitree.Stepper(i => Console.Write(i)); Console.WriteLine(); int minimumXZ = random.Next(1, test / 2); int maximumXZ = random.Next(1, test / 2) + test / 2; string minimumY = minimumXZ.ToString(); string maximumY = maximumXZ.ToString(); Console.Write(" Spacial Traversal [" + "(" + minimumXZ + ", \"" + minimumY + "\", " + minimumXZ + ")->" + "(" + maximumXZ + ", \"" + maximumY + "\", " + maximumXZ + ")]: "); omnitree.Stepper(i => Console.Write(i), minimumXZ, maximumXZ, minimumY, maximumY, minimumXZ, maximumXZ); Console.WriteLine(); // Note: this "look up" is just a very narrow spacial query that (since we know the data) // wil only give us one result. int lookUp = random.Next(0, test); string lookUpToString = lookUp.ToString(); Console.Write(" Look Up (" + lookUp + ", \"" + lookUpToString + "\", " + lookUp + "): "); omnitree.Stepper(i => Console.Write(i), lookUp, lookUp, lookUp.ToString(), lookUp.ToString(), lookUp, lookUp); Console.WriteLine(); // Ignoring dimensions on traversals example. // If you want to ignore a column on a traversal, you can do so like this: omnitree.Stepper(i => { /*Do Nothing*/ }, lookUp, lookUp, Omnitree.Bound <string> .None, Omnitree.Bound <string> .None, Omnitree.Bound <decimal> .None, Omnitree.Bound <decimal> .None); Console.Write(" Counting Items In a Space [" + "(" + minimumXZ + ", \"" + minimumY + "\", " + minimumXZ + ")->" + "(" + maximumXZ + ", \"" + maximumY + "\", " + maximumXZ + ")]: "); omnitree.CountSubSpace( minimumXZ, maximumXZ, minimumY, maximumY, minimumXZ, maximumXZ); Console.WriteLine(); int removalMinimum = random.Next(1, test / 2); int removalMaximum = random.Next(1, test / 2) + test / 2; string removalMinimumY = removalMinimum.ToString(); string removalMaximumY = removalMaximum.ToString(); Console.Write(" Remove (" + removalMinimum + "-" + removalMaximum + "): "); omnitree.Remove( removalMinimum, removalMaximum, removalMinimumY, removalMaximumY, removalMinimum, removalMaximum); omnitree.Stepper(i => Console.Write(i)); Console.WriteLine(); Console.WriteLine(" Dimensions: " + omnitree.Dimensions); Console.WriteLine(" Count: " + omnitree.Count); omnitree.Clear(); // Clears the Omnitree Console.WriteLine(); } #endregion #region OmnitreeBounds { Console.WriteLine(" OmnitreeBounds--------------------------------------"); Console.WriteLine(); Console.WriteLine(" An Omnitree is an ND SPT that allows for"); Console.WriteLine(" multidimensional sorting. Any time you need to look"); Console.WriteLine(" items up based on multiple fields/properties, then"); Console.WriteLine(" you might want to use an Omnitree. If you need to"); Console.WriteLine(" perform ranged queries on multiple dimensions, then"); Console.WriteLine(" the Omnitree is the data structure for you."); Console.WriteLine(); Console.WriteLine(" The \"OmnitreePoints\" stores individual points (vectors),"); Console.WriteLine(" and the \"OmnitreeBounds\" stores bounded objects (spaces)."); Console.WriteLine(); IOmnitreeBounds <int, double, string, decimal> omnitree = new OmnitreeBoundsLinked <int, double, string, decimal>( // This is a location delegate. (how to locate the item along each dimension) (int index, out double min1, out double max1, out string min2, out string max2, out decimal min3, out decimal max3) => { string indexToString = index.ToString(); min1 = index; max1 = index; min2 = indexToString; max2 = indexToString; min3 = index; max3 = index; }); Console.Write(" Adding (0-" + (test - 1) + ")..."); for (int i = 0; i < test; i++) { omnitree.Add(i); } Console.WriteLine(); Console.Write(" Traversal: "); omnitree.Stepper(i => Console.Write(i)); Console.WriteLine(); int minimumXZ = random.Next(1, test / 2); int maximumXZ = random.Next(1, test / 2) + test / 2; string minimumY = minimumXZ.ToString(); string maximumY = maximumXZ.ToString(); Console.Write(" Spacial Traversal [" + "(" + minimumXZ + ", \"" + minimumY + "\", " + minimumXZ + ")->" + "(" + maximumXZ + ", \"" + maximumY + "\", " + maximumXZ + ")]: "); omnitree.StepperOverlapped(i => Console.Write(i), minimumXZ, maximumXZ, minimumY, maximumY, minimumXZ, maximumXZ); Console.WriteLine(); // Note: this "look up" is just a very narrow spacial query that (since we know the data) // wil only give us one result. int lookUpXZ = random.Next(0, test); string lookUpY = lookUpXZ.ToString(); Console.Write(" Look Up (" + lookUpXZ + ", \"" + lookUpY + "\", " + lookUpXZ + "): "); omnitree.StepperOverlapped(i => Console.Write(i), lookUpXZ, lookUpXZ, lookUpY, lookUpY, lookUpXZ, lookUpXZ); Console.WriteLine(); // Ignoring dimensions on traversals example. // If you want to ignore a dimension on a traversal, you can do so like this: omnitree.StepperOverlapped(i => { /*Do Nothing*/ }, lookUpXZ, lookUpXZ, // The "None" means there is no bound, so all values are valid Omnitree.Bound <string> .None, Omnitree.Bound <string> .None, Omnitree.Bound <decimal> .None, Omnitree.Bound <decimal> .None); Console.Write(" Counting Items In a Space [" + "(" + minimumXZ + ", \"" + minimumY + "\", " + minimumXZ + ")->" + "(" + maximumXZ + ", \"" + maximumY + "\", " + maximumXZ + ")]: " + omnitree.CountSubSpaceOverlapped( minimumXZ, maximumXZ, minimumY, maximumY, minimumXZ, maximumXZ)); Console.WriteLine(); int removalMinimumXZ = random.Next(1, test / 2); int removalMaximumXZ = random.Next(1, test / 2) + test / 2; string removalMinimumY = removalMinimumXZ.ToString(); string removalMaximumY = removalMaximumXZ.ToString(); Console.Write(" Remove (" + removalMinimumXZ + "-" + removalMaximumXZ + "): "); omnitree.RemoveOverlapped( removalMinimumXZ, removalMaximumXZ, removalMinimumY, removalMaximumY, removalMinimumXZ, removalMaximumXZ); omnitree.Stepper(i => Console.Write(i)); Console.WriteLine(); Console.WriteLine(" Dimensions: " + omnitree.Dimensions); Console.WriteLine(" Count: " + omnitree.Count); omnitree.Clear(); // Clears the Omnitree Console.WriteLine(); } #endregion #region KD Tree { Console.WriteLine(" KD Tree------------------------------------------------"); Console.WriteLine(); Console.WriteLine(" A KD Tree binary tree that stores points sorted along along an"); Console.WriteLine(" arbitrary number of dimensions. So it performs multidimensional"); Console.WriteLine(" sorting similar to the Omnitree (Quadtree/Octree) in Towel, but"); Console.WriteLine(" it uses a completely different algorithm and format."); Console.WriteLine(); Console.WriteLine(" The generic KD Tree in Towel is still in development."); Console.WriteLine(); } #endregion #region Graph { Console.WriteLine(" Graph------------------------------------------------"); Console.WriteLine(); Console.WriteLine(" A Graph is a data structure of nodes and edges. Nodes are values"); Console.WriteLine(" and edges are connections between those values. Graphs are often"); Console.WriteLine(" used to model real world data such as maps, and are often used in"); Console.WriteLine(" path finding algoritms. See the \"Algorithms\" example for path"); Console.WriteLine(" finding examples. This is just an example of how to make a graph."); Console.WriteLine(" A \"GraphSetOmnitree\" is an implementation where nodes are stored."); Console.WriteLine(" in a Set and edges are stored in an Omnitree (aka Quadtree)."); Console.WriteLine(); IGraph <int> graphSetOmnitree = new GraphSetOmnitree <int>(); Console.WriteLine(" Adding Nodes (0-" + (test - 1) + ")..."); for (int i = 0; i < test; i++) { graphSetOmnitree.Add(i); } int edgesPerNode = 3; Console.WriteLine(" Adding Random Edges (0-3 per node)..."); for (int i = 0; i < test; i++) { // lets use a heap to randomize the edges using random priorities IHeap <(int, int)> heap = new HeapArray <(int, int)>((x, y) => Compare.Wrap(x.Item2.CompareTo(y.Item2))); for (int j = 0; j < test; j++) { if (j != i) { heap.Enqueue((j, random.Next())); } } // dequeue some random edges from the heap and add them to the graph int randomEdgeCount = random.Next(edgesPerNode + 1); for (int j = 0; j < randomEdgeCount; j++) { graphSetOmnitree.Add(i, heap.Dequeue().Item1); } } Console.Write(" Nodes (Traversal): "); graphSetOmnitree.Stepper(i => Console.Write(i)); Console.WriteLine(); Console.WriteLine(" Edges (Traversal): "); graphSetOmnitree.Stepper((from, to) => Console.WriteLine(" " + from + "->" + to)); Console.WriteLine(); int a = random.Next(0, test); Console.Write(" Neighbors (" + a + "):"); graphSetOmnitree.Neighbors(a, i => Console.Write(" " + i)); Console.WriteLine(); int b = random.Next(0, test / 2); int c = random.Next(test / 2, test); Console.WriteLine(" Are Adjacent (" + b + ", " + c + "): " + graphSetOmnitree.Adjacent(b, c)); Console.WriteLine(" Node Count: " + graphSetOmnitree.NodeCount); Console.WriteLine(" Edge Count: " + graphSetOmnitree.EdgeCount); graphSetOmnitree.Clear(); // Clears the graph Console.WriteLine(); } #endregion #region Trie { Console.WriteLine(" Trie------------------------------------------------"); Console.WriteLine(); Console.WriteLine(" A Trie is a tree where portions of the data are stored in each node"); Console.WriteLine(" such that when you traverse the tree to a leaf, you have read the contents"); Console.WriteLine(" of that leaf along the way. Because of this, a Trie allows for its values"); Console.WriteLine(" to share data, which is a form of compression. So a Trie may be used to save"); Console.WriteLine(" memory. A trie may also be a very useful tool in pattern matching, because"); Console.WriteLine(" it allows for culling based are portions of the data."); Console.WriteLine(); Console.WriteLine(" The generic Trie in Towel is still in development."); Console.WriteLine(); } #endregion Console.WriteLine("============================================"); Console.WriteLine("Examples Complete..."); Console.ReadLine(); }
internal static T[][] Build <UNITS, T>() { int size = Convert.ToInt32(Extensions.GetMaxEnumValue <UNITS>()); T[][] conversionFactorTable = Extensions.ConstructSquareJagged <T>(size + 1); foreach (Enum A_unit in Enum.GetValues(typeof(UNITS))) { int A = Convert.ToInt32(A_unit); // handle metric units first MetricUnitAttribute A_metric = A_unit.GetEnumAttribute <MetricUnitAttribute>(); if (!(A_metric is null)) { foreach (Enum B_units in Enum.GetValues(typeof(UNITS))) { int B = Convert.ToInt32(B_units); MetricUnitAttribute B_metric = B_units.GetEnumAttribute <MetricUnitAttribute>(); if (!(B_metric is null)) { int metricDifference = (int)A_metric.MetricUnits - (int)B_metric.MetricUnits; conversionFactorTable[A][B] = Compute.Power(Constant <T> .Ten, Compute.FromInt32 <T>(metricDifference)); }
internal void Reset() { Compute.Reset(); Vertex.Reset(); Fragment.Reset(); }
public double Calculate(OperationType operationType) { return(CanCalculate ? Compute(operationType)(GetOperand(), GetOperand()) : (default));
protected override void GenerateMethod(Node node, StreamWriter stream, string indent) { base.GenerateMethod(node, stream, indent); Compute compute = node as Compute; if (compute == null) { return; } stream.WriteLine("{0}\t\tprotected override EBTStatus update_impl(behaviac.Agent pAgent, behaviac.EBTStatus childStatus)", indent); stream.WriteLine("{0}\t\t{{", indent); stream.WriteLine("{0}\t\t\tEBTStatus result = EBTStatus.BT_SUCCESS;", indent); if (compute.Opl != null && compute.Opr1 != null && compute.Opr2 != null) { string typeName = Plugin.GetNativeTypeName(compute.Opr1.ValueType); typeName = typeName.Replace("::", "."); RightValueCsExporter.GenerateCode(node, compute.Opr1, stream, indent + "\t\t\t", typeName, "opr1", "opr1"); RightValueCsExporter.GenerateCode(node, compute.Opr2, stream, indent + "\t\t\t", typeName, "opr2", "opr2"); string oprStr = string.Empty; switch (compute.Operator) { case ComputeOperator.Add: oprStr = "opr1 + opr2"; break; case ComputeOperator.Sub: oprStr = "opr1 - opr2"; break; case ComputeOperator.Mul: oprStr = "opr1 * opr2"; break; case ComputeOperator.Div: oprStr = "opr1 / opr2"; break; default: Debug.Check(false, "The operator is wrong!"); break; } oprStr = string.Format("({0})({1})", typeName, oprStr); PropertyDef prop = compute.Opl.Property; if (prop != null) { string property = PropertyCsExporter.GetProperty(node, prop, compute.Opl.ArrayIndexElement, stream, indent + "\t\t\t", "opl", "compute"); string propName = prop.BasicName.Replace("[]", ""); if (prop.IsArrayElement && compute.Opl.ArrayIndexElement != null) { ParameterCsExporter.GenerateCode(node, compute.Opl.ArrayIndexElement, stream, indent + "\t\t\t", "int", "opl_index", "compute_opl"); property = string.Format("({0})[opl_index]", property); } if (!prop.IsArrayElement && (prop.IsPar || prop.IsCustomized)) { string propBasicName = prop.BasicName.Replace("[]", ""); uint id = Behaviac.Design.CRC32.CalcCRC(propBasicName); string agentName = PropertyCsExporter.GetGenerateAgentName(prop, "opl", "compute"); string typename = DataCsExporter.GetGeneratedNativeType(prop.NativeType); stream.WriteLine("{0}\t\t\t{1}.SetVariable<{2}>(\"{3}\", {4}u, {5});", indent, agentName, typename, propBasicName, id, oprStr); } else { stream.WriteLine("{0}\t\t\t{1} = {2};", indent, property, oprStr); } } if (compute.Opr1.IsMethod) { RightValueCsExporter.PostGenerateCode(compute.Opr1, stream, indent + "\t\t\t", typeName, "opr1", string.Empty); } if (compute.Opr2.IsMethod) { RightValueCsExporter.PostGenerateCode(compute.Opr2, stream, indent + "\t\t\t", typeName, "opr2", string.Empty); } } stream.WriteLine("{0}\t\t\treturn result;", indent); stream.WriteLine("{0}\t\t}}", indent); }
internal MachineLearningComputeData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, ManagedServiceIdentity identity, string location, IDictionary <string, string> tags, MachineLearningSku sku, Compute properties) : base(id, name, resourceType, systemData) { Identity = identity; Location = location; Tags = tags; Sku = sku; Properties = properties; }
public void Execute44ShouldReturn701408733() { var result = Compute.Execute(new[] { "44" }); Assert.Equal(701408733, result[0]); }
static void Main(string[] args) { Console.WriteLine("You are runnning the Algorithms example."); Console.WriteLine("======================================================"); Console.WriteLine(); #region Sorting { // Note: these functions are not restricted to array types. You can use the // overloads with "Get" and "Assign" delegates to use them on any int-indexed // data structure. Console.WriteLine(" Sorting Algorithms----------------------"); Console.WriteLine(); int[] dataSet = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; Console.Write(" Data Set:" + string.Join(", ", dataSet.Select(x => x.ToString()))); Console.WriteLine(); // Shuffling (Randomizing) Sort.Shuffle(dataSet); Console.Write(" Shuffle (Randomizing): " + string.Join(", ", dataSet.Select(x => x.ToString()))); Console.WriteLine(); // Bubble Sort.Bubble(dataSet); Console.Write(" Bubble: " + string.Join(", ", dataSet.Select(x => x.ToString()))); Console.WriteLine(); Console.WriteLine(" shuffling dataSet..."); Sort.Shuffle(dataSet); // Selection Sort.Selection(dataSet); Console.Write(" Selection: " + string.Join(", ", dataSet.Select(x => x.ToString()))); Console.WriteLine(); Console.WriteLine(" shuffling dataSet..."); Sort.Shuffle(dataSet); // Insertion Sort.Insertion(dataSet); Console.Write(" Insertion: " + string.Join(", ", dataSet.Select(x => x.ToString()))); Console.WriteLine(); Console.WriteLine(" shuffling dataSet..."); Sort.Shuffle(dataSet); // Quick Sort.Quick(dataSet); Console.Write(" Quick: " + string.Join(", ", dataSet.Select(x => x.ToString()))); Console.WriteLine(); Console.WriteLine(" shuffling dataSet..."); Sort.Shuffle(dataSet); // Merge Sort.Merge(dataSet); Console.Write(" Merge: " + string.Join(", ", dataSet.Select(x => x.ToString()))); Console.WriteLine(); Console.WriteLine(" shuffling dataSet..."); Sort.Shuffle(dataSet); // Heap Sort.Heap(dataSet); Console.Write(" Heap: " + string.Join(", ", dataSet.Select(x => x.ToString()))); Console.WriteLine(); Console.WriteLine(" shuffling dataSet..."); Sort.Shuffle(dataSet); // OddEven Sort.OddEven(dataSet); Console.Write(" OddEven: " + string.Join(", ", dataSet.Select(x => x.ToString()))); Console.WriteLine(); //Console.WriteLine(" shuffling dataSet..."); //Sort.Shuffle(dataSet); //// Slow //Sort<int>.Slow(Logic.compare, get, set, 0, dataSet.Length); //Console.Write("Slow: " + string.Join(", ", dataSet.Select(x => x.ToString()))); //Console.WriteLine(); Console.WriteLine(" shuffling dataSet..."); Sort.Shuffle(dataSet); // Bogo Console.Write(" Bogo: Disabled (takes forever)"); //Sort.Bogo(dataSet); //Console.Write(" Bogo: " + string.Join(", ", dataSet.Select(x => x.ToString()))); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); } #endregion #region Graph Search (Using Graph Data Structure) { Console.WriteLine(" Graph Searching----------------------"); Console.WriteLine(); // make a graph IGraph <int> graph = new GraphSetOmnitree <int>() { // add nodes 0, 1, 2, 3, // add edges { 0, 1 }, { 1, 2 }, { 2, 3 }, { 0, 3 }, // visualization // // 0 --------> 1 // | | // | | // | | // v v // 3 <-------- 2 }; // make a heuristic function int heuristic(int node) { switch (node) { case 0: return(3); case 1: return(6); case 2: return(1); case 3: return(0); default: throw new NotImplementedException(); } } // make a cost function int cost(int from, int to) { if (from == 0 && to == 1) { return(1); } if (from == 1 && to == 2) { return(2); } if (from == 2 && to == 3) { return(5); } if (from == 0 && to == 3) { return(99); } throw new Exception("invalid path cost computation"); } // make a goal function bool goal(int node) { if (node == 3) { return(true); } else { return(false); } } // run A* the algorithm Stepper <int> aStar_path = Search.Graph(0, graph, heuristic, cost, goal); Console.Write(" A* Path: "); if (aStar_path != null) { aStar_path(i => Console.Write(i + " ")); } else { Console.Write("none"); } Console.WriteLine(); // run the Greedy algorithm Stepper <int> greedy_path = Search.Graph(0, graph, heuristic, goal); Console.Write(" Greedy Path: "); if (greedy_path != null) { greedy_path(i => Console.Write(i + " ")); } else { Console.Write("none"); } Console.WriteLine(); Console.WriteLine(); } #endregion #region Graph Search (Vector Game-Style Example) { Console.WriteLine(" Graph Searching (Vector Game-Style Example)-------------------"); Console.WriteLine(); Console.WriteLine(" Debug the code. The path is to large to write to the console."); Console.WriteLine(); // Lets say you are coding enemy AI and you want the AI to find a path towards the player // in order to attack them. Here are their starting positions: Vector <float> enemyLocation = new Vector <float>(-100f, 0f, -50f); Vector <float> playerLocation = new Vector <float>(200f, 0f, -50f); float enemyAttackRange = 3f; // enemy has a melee attack with 3 range // Lets say most of the terrain is open, but there is a big rock in between them that they // must go around. Vector <float> rockLocation = new Vector <float>(15f, 0f, -40f); float rockRadius = 20f; // Make sure we don't re-use locations (must be wiped after running the algorithm) ISet <Vector <float> > alreadyUsed = new SetHashLinked <Vector <float> >(); Vector <float> validationVectorStorage = null; // storage to prevent a ton of vectors from being allocated // So, we just need to validate movement locations (make sure the path finding algorithm // ignores locations inside the rock) bool validateMovementLocation(Vector <float> location) { // if the location is inside the rock, it is not a valid movement location.Subtract(rockLocation, ref validationVectorStorage); float magnitude = validationVectorStorage.Magnitude; if (magnitude <= rockRadius) { return(false); } // NOTE: If you are running a physics engine, you might be able to just call it to validate a location. // if the location was already used, then let's consider it invalid, because // another path (which is faster) has already reached that location if (alreadyUsed.Contains(location)) { return(false); } return(true); } // Now we need the neighbor function (getting the neighbors of the current location). void neighborFunction(Vector <float> currentLocation, Step <Vector <float> > neighbors) { // NOTES: // - This neighbor function has a 90 degree per-node resolution (360 / 4 [north/south/east/west] = 90). // - This neighbor function has a 1 unit per-node distance resolution, because we went 1 unit in each direction. // RECOMMENDATIONS: // - If the path finding is failing, you may need to increase the resolution. // - If the algorithm is running too slow, you may need to reduce the resolution. float distanceResolution = 1; float x = currentLocation.X; float y = currentLocation.Y; float z = currentLocation.Z; // Note: I'm using the X-axis and Z-axis here, but which axis you need to use // depends on your environment. Your "north" could be along the Y-axis for example. Vector <float> north = new Vector <float>(x + distanceResolution, y, z); if (validateMovementLocation(north)) { alreadyUsed.Add(north); // mark location as used neighbors(north); } Vector <float> east = new Vector <float>(x, y, z + distanceResolution); if (validateMovementLocation(east)) { alreadyUsed.Add(east); // mark location as used neighbors(east); } Vector <float> south = new Vector <float>(x - distanceResolution, y, z); if (validateMovementLocation(south)) { alreadyUsed.Add(south); // mark location as used neighbors(south); } Vector <float> west = new Vector <float>(x, y, z - distanceResolution); if (validateMovementLocation(west)) { alreadyUsed.Add(west); // mark location as used neighbors(west); } } Vector <float> heuristicVectorStorage = null; // storage to prevent a ton of vectors from being allocated // Heuristic function (how close are we to the goal) float heuristicFunction(Vector <float> currentLocation) { // The goal is the player's location, so we just need our distance from the player. currentLocation.Subtract(playerLocation, ref heuristicVectorStorage); return(heuristicVectorStorage.Magnitude); } // Lets say there is a lot of mud around the rock, and the mud makes our player move at half their normal speed. // Our path finding needs to find the fastest route to the player, whether it be through the mud or not. Vector <float> mudLocation = new Vector <float>(15f, 0f, -70f); float mudRadius = 30f; Vector <float> costVectorStorage = null; // storage to prevent a ton of vectors from being allocated // Cost function float costFunction(Vector <float> from, Vector <float> to) { // If the location we are moving to is in the mud, lets adjust the // cost because mud makes us move slower. to.Subtract(mudLocation, ref costVectorStorage); float magnitude = costVectorStorage.Magnitude; if (magnitude <= mudRadius) { return(2f); } // neither location is in the mud, it is just a standard movement at normal speed. return(1f); } Vector <float> goalVectorStorage = null; // storage to prevent a ton of vectors from being allocated // Goal function bool goalFunction(Vector <float> currentLocation) { // if the player is within the enemy's attack range WE FOUND A PATH! :) currentLocation.Subtract(playerLocation, ref goalVectorStorage); float magnitude = goalVectorStorage.Magnitude; if (magnitude <= enemyAttackRange) { return(true); } // the enemy is not yet within attack range return(false); } // We have all the necessary parameters. Run the pathfinding algorithms! Stepper <Vector <float> > aStarPath = Search.Graph( enemyLocation, neighborFunction, heuristicFunction, costFunction, goalFunction); // Flush the already used markers before running the Greedy algorithm. // Normally you won't run two algorithms for the same graph/location, but // we are running both algorithms in this example to demonstrate the // differences between them. alreadyUsed.Clear(); Stepper <Vector <float> > greedyPath = Search.Graph( enemyLocation, neighborFunction, heuristicFunction, goalFunction); // NOTE: If there is no valid path, then "Search.Graph" will return "null." // For this example, I know that there will be a valid path so I did not // include a null check. // Lets convert the paths into arrays so you can look at them in the debugger. :) Vector <float>[] aStarPathArray = aStarPath.ToArray(); Vector <float>[] greedyPathArray = greedyPath.ToArray(); // lets calculate the movement cost of each path to see how they compare float astartTotalCost = Compute.Add <float>(step => { for (int i = 0; i < aStarPathArray.Length - 1; i++) { step(costFunction(aStarPathArray[i], aStarPathArray[i + 1])); } }); float greedyTotalCost = Compute.Add <float>(step => { for (int i = 0; i < greedyPathArray.Length - 1; i++) { step(costFunction(greedyPathArray[i], greedyPathArray[i + 1])); } }); // Notice that that the A* algorithm produces a less costly path than the Greedy, // meaning that it is faster. The Greedy path went through the mud, but the A* path // took the longer route around the other side of the rock, which ended up being faster // than running through the mud. } #endregion Console.WriteLine(); Console.WriteLine("============================================"); Console.WriteLine("Example Complete..."); Console.ReadLine(); }
public void Sum(int firstNumber, int secondNumber) { NumberOne.SetText(firstNumber.ToString()); NumberTwo.SetText(secondNumber.ToString()); Compute.Click(); }
/***************************************************/ /**** Private Helper Methods ****/ /***************************************************/ private void SerializeDiscriminatedValue(BsonSerializationContext context, BsonSerializationArgs args, object value, Type actualType) { if (actualType.Name == "RuntimeMethodInfo" || actualType.Name == "RuntimeConstructorInfo") { actualType = typeof(MethodBase); } else if (actualType.Name == "RuntimeType") { actualType = typeof(Type); } else if (value is Enum) { actualType = typeof(Enum); } if (!BsonClassMap.IsClassMapRegistered(actualType)) { Compute.RegisterClassMap(actualType); } var serializer = BsonSerializer.LookupSerializer(actualType); if (serializer.GetType().Name == "EnumerableInterfaceImplementerSerializer`2" && context.Writer.State == BsonWriterState.Initial) { if (!m_FallbackSerialisers.ContainsKey(actualType)) { CreateFallbackSerialiser(actualType); } serializer = m_FallbackSerialisers[actualType]; } var polymorphicSerializer = serializer as IBsonPolymorphicSerializer; if (polymorphicSerializer != null && polymorphicSerializer.IsDiscriminatorCompatibleWithObjectSerializer) { serializer.Serialize(context, args, value); } else { if (context.IsDynamicType != null && context.IsDynamicType(value.GetType())) { args.NominalType = actualType; serializer.Serialize(context, args, value); } else { var bsonWriter = context.Writer; if (actualType.Name == "Dictionary`2") { Type keyType = actualType.GenericTypeArguments[0]; if (keyType == typeof(string)) { serializer.Serialize(context, value); } else { DictionarySerializer dicSerialiser = new DictionarySerializer(); dicSerialiser.Serialize(context, value); } } else { serializer.Serialize(context, value); } } } }
/***************************************************/ private object DeserializeDiscriminatedValue(BsonDeserializationContext context, BsonDeserializationArgs args) { // First try to recover the object type IBsonReader reader = context.Reader; BsonReaderBookmark bookmark = reader.GetBookmark(); Type actualType = typeof(CustomObject); try { actualType = _discriminatorConvention.GetActualType(reader, typeof(object)); } catch { try { context.Reader.ReturnToBookmark(bookmark); DeprecatedSerializer deprecatedSerialiser = new DeprecatedSerializer(); return(deprecatedSerialiser.Deserialize(context, args)); } catch { } } context.Reader.ReturnToBookmark(bookmark); if (actualType == null) { return(null); } // Handle the special case where the type is object if (actualType == typeof(object)) { BsonType currentBsonType = reader.GetCurrentBsonType(); if (currentBsonType == BsonType.Document && context.DynamicDocumentSerializer != null) { return(context.DynamicDocumentSerializer.Deserialize(context, args)); } reader.ReadStartDocument(); reader.ReadEndDocument(); return(new object()); } // Handle the general case of finding the correct deserialiser and calling it try { if (!BsonClassMap.IsClassMapRegistered(actualType)) { Compute.RegisterClassMap(actualType); // LookupSerializer creates the classMap if it doesn't exist so important to do it through our own method } IBsonSerializer bsonSerializer = BsonSerializer.LookupSerializer(actualType); if (bsonSerializer.GetType().Name == "EnumerableInterfaceImplementerSerializer`2" && context.Reader.CurrentBsonType == BsonType.Document) { if (!m_FallbackSerialisers.ContainsKey(actualType)) { CreateFallbackSerialiser(actualType); } bsonSerializer = m_FallbackSerialisers[actualType]; } else if (actualType.Name == "Dictionary`2" && context.Reader.CurrentBsonType == BsonType.Document) { DictionarySerializer dicSerialiser = new DictionarySerializer(); return(dicSerialiser.Deserialize(context, args)); } return(bsonSerializer.Deserialize(context, args)); } catch (Exception e) { if (e.Message.Contains("Could not load file or assembly")) { Engine.Reflection.Compute.RecordError(e.Message); } context.Reader.ReturnToBookmark(bookmark); DeprecatedSerializer deprecatedSerialiser = new DeprecatedSerializer(); return(deprecatedSerialiser.Deserialize(context, args)); } }
static void Main(string[] args) { Console.WriteLine("Welcome To SevenFramework! :)"); Console.WriteLine(); Console.WriteLine("You are runnning the Mathematics example."); Console.WriteLine("=========================================="); Console.WriteLine(); #region Basic Operations Console.WriteLine(" Basics----------------------------------------------"); Console.WriteLine(); // Negation Console.WriteLine(" Compute<int>.Negate(7): " + Compute <int> .Negate(7)); // Addition Console.WriteLine(" Compute<double>.Add(7, 7): " + Compute <decimal> .Add(7, 7)); // Subtraction Console.WriteLine(" Compute<float>.Subtract(14, 7): " + Compute <float> .Subtract(14, 7)); // Multiplication Console.WriteLine(" Compute<long>.Multiply(7, 7): " + Compute <long> .Multiply(7, 7)); // Division Console.WriteLine(" Compute<short>.Divide(14, 7): " + Compute <short> .Divide(14, 7)); // Absolute Value Console.WriteLine(" Compute<decimal>.AbsoluteValue(-7): " + Compute <double> .AbsoluteValue(-7)); // Clamp Console.WriteLine(" Compute<Fraction>.Clamp(-123, 7, 14): " + Compute <Fraction> .Clamp(-123, 7, 14)); // Maximum Console.WriteLine(" Compute<byte>.Maximum(1, 2, 3): " + Compute <byte> .Maximum((Step <byte> step) => { step(1); step(2); step(3); })); // Minimum Console.WriteLine(" Compute<Integer>.Minimum(1, 2, 3): " + Compute <Integer> .Minimum((Step <Integer> step) => { step(1); step(2); step(3); })); // Less Than Console.WriteLine(" Compute<Fraction128>.LessThan(1, 2): " + Compute <Fraction128> .LessThan(1, 2)); // Greater Than Console.WriteLine(" Compute<Fraction64>.GreaterThan(1, 2): " + Compute <Fraction64> .GreaterThan(1, 2)); // Compare Console.WriteLine(" Compute<Fraction32>.Compare(7, 7): " + Compute <Fraction32> .Compare(7, 7)); // Equate Console.WriteLine(" Compute<int>.Equate(7, 6): " + Compute <int> .Equate(7, 6)); // EqualsLeniency Console.WriteLine(" Compute<int>.EqualsLeniency(2, 1, 1): " + Compute <int> .EqualsLeniency(2, 1, 1)); Console.WriteLine(); #endregion #region Number Theory Console.WriteLine(" Number Theory--------------------------------------"); Console.WriteLine(); // Prime Checking int prime_check = random.Next(0, 100000); Console.WriteLine(" IsPrime(" + prime_check + "): " + Compute <int> .IsPrime(prime_check)); // GCF Checking int[] gcf = new int[] { random.Next(0, 500) * 2, random.Next(0, 500) * 2, random.Next(0, 500) * 2 }; Console.WriteLine(" GCF(" + gcf[0] + ", " + gcf[1] + ", " + gcf[2] + "): " + Compute <int> .GreatestCommonFactor(gcf.Stepper())); // LCM Checking int[] lcm = new int[] { random.Next(0, 500) * 2, random.Next(0, 500) * 2, random.Next(0, 500) * 2 }; Console.WriteLine(" LCM(" + lcm[0] + ", " + lcm[1] + ", " + lcm[2] + "): " + Compute <int> .LeastCommonMultiple(lcm.Stepper())); Console.WriteLine(); #endregion #region Range //Console.WriteLine(" Range---------------------------------------------"); //Console.WriteLine(); //Console.WriteLine(" 1D int"); //{ //Range<int> range1 = new Range<int>(1, 7); //Console.WriteLine(" range1: " + range1); //Range<int> range2 = new Range<int>(4, 10); //Console.WriteLine(" range2: " + range2); //Range<int>[] range3 = range1 ^ range2; //Console.WriteLine(" range1 ^ range2 (Complement): " + range3[0]); //Range<int>[] range4 = range1 | range2; //Console.WriteLine(" range1 | range2 (Union): " + range4[0]); //Range<int> range5 = range1 & range2; //Console.WriteLine(" range1 & range2 (Intersection): " + range5); //} //Console.WriteLine(" 2D double"); //{ //Range<double> range1 = new Range<double>(new Vector<double>(1, 2), new Vector<double>(7, 8)); //Console.WriteLine(" range1: " + range1); //Range<double> range2 = new Range<double>(new Vector<double>(4, 5), new Vector<double>(10, 11)); //Console.WriteLine(" range2: " + range2); //Range<double>[] range3 = range1 ^ range2; //Console.WriteLine(" range1 ^ range2 (Complement): Not Yet Implemented"); //Range<double>[] range4 = range1 | range2; //Console.WriteLine(" range1 | range2 (Union): Not Yet Implemented");// + range4); //Range<double> range5 = range1 & range2; //Console.WriteLine(" range1 & range2 (Intersection): " + range5); //} //Console.WriteLine(); #endregion #region Angles //Console.WriteLine(" Angles--------------------------------------"); //Console.WriteLine(); //Angle<double> angle1 = Angle<double>.Factory_Degrees(90d); //Console.WriteLine(" angle1 = " + angle1.Radians + " radians"); //Angle<double> angle2 = Angle<double>.Factory_Turns(0.5d); //Console.WriteLine(" angle2 = " + angle1.Turns + " turns"); //Console.WriteLine(" angle1 + angle2 = " + (angle1 + angle2).Radians + " radians"); //Console.WriteLine(" angle2 - angle1 = " + (angle1 + angle2).Radians + " radians"); //Console.WriteLine(" angle1 * 2 = " + (angle1 * 2).Radians + " radians"); //Console.WriteLine(" angle1 / 2 = " + (angle1 / 2).Radians + " radians"); //Console.WriteLine(" angle1 > angle2 = " + (angle1 > angle2)); //Console.WriteLine(" angle1 == angle2 = " + (angle1 == angle2)); //Console.WriteLine(" angle1 * 2 == angle2 = " + (angle1 * 2 == angle2)); //Console.WriteLine(" angle1 != angle2 = " + (angle1 != angle2)); //Console.WriteLine(); #endregion #region Fraction //Console.WriteLine(" Fractions-----------------------------------"); //Console.WriteLine(); //Fraction128 fraction1 = new Fraction128(2.5); //Console.WriteLine(" fraction1 = " + fraction1); //Fraction128 fraction2 = new Fraction128(3.75); //Console.WriteLine(" fraction2 = " + fraction2); //Console.WriteLine(" fraction1 + fraction2 = " + fraction1 + fraction2); //Console.WriteLine(" fraction2 - fraction1 = " + fraction1 + fraction2); //Console.WriteLine(" fraction1 * 2 = " + fraction1 * 2); //Console.WriteLine(" fraction1 / 2 = " + fraction1 / 2); //Console.WriteLine(" fraction1 > fraction2 = " + (fraction1 > fraction2)); //Console.WriteLine(" fraction1 == fraction2 = " + (fraction1 == fraction2)); //Console.WriteLine(" fraction1 * 2 == fraction2 = " + (fraction1 * 2 == fraction2)); //Console.WriteLine(" fraction1 != fraction2 = " + (fraction1 != fraction2)); //Console.WriteLine(); #endregion #region Statistics Console.WriteLine(" Statistics-----------------------------------------"); Console.WriteLine(); // Makin some random data... double mode_temp = random.NextDouble() * 100; double[] statistics_data = new double[] { random.NextDouble() * 100, mode_temp, random.NextDouble() * 100, random.NextDouble() * 100, random.NextDouble() * 100, random.NextDouble() * 100, mode_temp }; // Print the data to the console... Console.WriteLine(" data: [" + string.Format("{0:0.00}", statistics_data[0]) + ", " + string.Format("{0:0.00}", statistics_data[1]) + ", " + string.Format("{0:0.00}", statistics_data[2]) + ", " + string.Format("{0:0.00}", statistics_data[3]) + ", " + string.Format("{0:0.00}", statistics_data[4]) + ", " + string.Format("{0:0.00}", statistics_data[5]) + ", " + string.Format("{0:0.00}", statistics_data[6]) + "]"); Console.WriteLine(); // Mean Console.WriteLine(" Mean(data): " + string.Format("{0:0.00}", Compute <double> .Mean(statistics_data.Stepper()))); // Median Console.WriteLine(" Median(data): " + string.Format("{0:0.00}", Compute <double> .Median(statistics_data.Stepper()))); // Mode Console.WriteLine(" Mode(data): "); Heap <Link <double, int> > modes = Compute <double> .Mode(statistics_data.Stepper()); while (modes.Count > 0) { Link <double, int> link = modes.Dequeue(); Console.WriteLine(" Point: " + string.Format("{0:0.00}", link.One) + " Occurences: " + link.Two); } Console.WriteLine(); // Geometric Mean Console.WriteLine(" Geometric Mean(data): " + string.Format("{0:0.00}", Compute <double> .GeometricMean(statistics_data.Stepper()))); // Range Range <double> range = Compute <double> .Range(statistics_data.Stepper()); Console.WriteLine(" Range(data): " + string.Format("{0:0.00}", range.Min) + "-" + string.Format("{0:0.00}", range.Max)); // Variance Console.WriteLine(" Variance(data): " + string.Format("{0:0.00}", Compute <double> .Variance(statistics_data.Stepper()))); // Standard Deviation Console.WriteLine(" Standard Deviation(data): " + string.Format("{0:0.00}", Compute <double> .StandardDeviation(statistics_data.Stepper()))); // Mean Deviation Console.WriteLine(" Mean Deviation(data): " + string.Format("{0:0.00}", Compute <double> .MeanDeviation(statistics_data.Stepper()))); Console.WriteLine(); // Quantiles //double[] quatiles = Statistics<double>.Quantiles(4, statistics_data.Stepper()); //Console.Write(" Quartiles(data):"); //foreach (double i in quatiles) // Console.Write(string.Format(" {0:0.00}", i)); //Console.WriteLine(); //Console.WriteLine(); #endregion #region Algebra Console.WriteLine(" Algebra---------------------------------------------"); Console.WriteLine(); // Prime Factorization int prime_factors = random.Next(0, 100000); Console.Write(" Prime Factors(" + prime_factors + "): "); Compute <int> .FactorPrimes(prime_factors, (int i) => { Console.Write(i + " "); }); Console.WriteLine(); Console.WriteLine(); // Logarithms int log_1 = random.Next(0, 11), log_2 = random.Next(0, 100000); Console.WriteLine(" log_" + log_1 + "(" + log_2 + "): " + string.Format("{0:0.00}", Compute <double> .Logarithm((double)log_1, (double)log_2))); Console.WriteLine(); // Summation double[] summation_values = new double[] { random.NextDouble(), random.NextDouble(), random.NextDouble(), random.NextDouble(), }; double summation = Compute <double> .Summation(summation_values.Stepper()); Console.Write(" Σ (" + string.Format("{0:0.00}", summation_values[0])); for (int i = 1; i < summation_values.Length; i++) { Console.Write(", " + string.Format("{0:0.00}", summation_values[i])); } Console.WriteLine(") = " + string.Format("{0:0.00}", summation)); Console.WriteLine(); #endregion #region Combinatorics Console.WriteLine(" Combinatorics--------------------------------------"); Console.WriteLine(); // Factorials Console.WriteLine(" 7!: " + Compute <int> .Factorial(7)); Console.WriteLine(); // Combinations Console.WriteLine(" 7! / (3! * 4!): " + Compute <int> .Combinations(7, new int[] { 3, 4 })); Console.WriteLine(); // Choose Console.WriteLine(" 7 choose 2: " + Compute <int> .Choose(7, 2)); Console.WriteLine(); #endregion #region Linear Algebra Console.WriteLine(" Linear Algebra------------------------------------"); Console.WriteLine(); // Vector Construction Vector <double> V = new double[] { random.NextDouble(), random.NextDouble(), random.NextDouble(), random.NextDouble(), }; Console.WriteLine(" Vector<double> V: "); ConsoleWrite(V); // Vctor Negation Console.WriteLine(" -V: "); ConsoleWrite(-V); // Vector Addition Console.WriteLine(" V + V (aka 2V): "); ConsoleWrite(V + V); // Vector Multiplication Console.WriteLine(" V * 2: "); ConsoleWrite(V * 2); // Vector Division Console.WriteLine(" V / 2: "); ConsoleWrite(V / 2); // Vector Dot Product Console.WriteLine(" V dot V: " + Vector <double> .DotProduct(V, V)); Console.WriteLine(); // Vector Cross Product Vector <double> V3 = new double[] { random.NextDouble(), random.NextDouble(), random.NextDouble(), }; Console.WriteLine(" Vector<double> V3: "); ConsoleWrite(V3); Console.WriteLine(" V3 cross V3: "); ConsoleWrite(Vector <double> .CrossProduct(V3, V3)); // Matrix Construction Matrix <double> M = (Matrix <double>) new double[, ] { { random.NextDouble(), random.NextDouble(), random.NextDouble(), random.NextDouble() }, { random.NextDouble(), random.NextDouble(), random.NextDouble(), random.NextDouble() }, { random.NextDouble(), random.NextDouble(), random.NextDouble(), random.NextDouble() }, { random.NextDouble(), random.NextDouble(), random.NextDouble(), random.NextDouble() }, }; Console.WriteLine(" Matrix<double> M: "); ConsoleWrite(M); // Matrix Negation Console.WriteLine(" -M: "); ConsoleWrite(-M); // Matrix Addition Console.WriteLine(" M + M (aka 2M): "); ConsoleWrite(M + M); // Matrix Subtraction Console.WriteLine(" M - M: "); ConsoleWrite(M - M); // Matrix Multiplication Console.WriteLine(" M * M (aka M ^ 2): "); ConsoleWrite(M * M); // If you have a large matrix that you want to multi-thread the multiplication, // use the function: "LinearAlgebra.Multiply_parallel". This function will // automatically parrallel the multiplication to the number of cores on your // personal computer. // Matrix Power Console.WriteLine(" M ^ 3: "); ConsoleWrite(M ^ 3); // Matrix Multiplication Console.WriteLine(" minor(M, 1, 1): "); ConsoleWrite(M.Minor(1, 1)); // Matrix Reduced Row Echelon Console.WriteLine(" rref(M): "); ConsoleWrite(Matrix <double> .ReducedEchelon(M)); // Matrix Determinant Console.WriteLine(" determinent(M): " + string.Format("{0:0.00}", Matrix <double> .Determinent(M))); Console.WriteLine(); // Matrix-Vector Multiplication Console.WriteLine(" M * V: "); ConsoleWrite(M * V); // Matrix Lower-Upper Decomposition Matrix <double> l, u; Matrix <double> .DecomposeLU(M, out l, out u); Console.WriteLine(" Lower-Upper Decomposition:"); Console.WriteLine(); Console.WriteLine(" lower(M):"); ConsoleWrite(l); Console.WriteLine(" upper(M):"); ConsoleWrite(u); // Quaternion Construction Quaternion <double> Q = new Quaternion <double>( random.NextDouble(), random.NextDouble(), random.NextDouble(), 1.0d); Console.WriteLine(" Quaternion<double> Q: "); ConsoleWrite(Q); // Quaternion Addition Console.WriteLine(" Q + Q (aka 2Q):"); ConsoleWrite(Q + Q); // Quaternion-Vector Rotation Console.WriteLine(" Q * V3 * Q':"); // Note: the vector should be normalized on the 4th component // for a proper rotation. (I did not do that) ConsoleWrite(V3.RotateBy(Q)); #endregion #region Convex Optimization //Console.WriteLine(" Convex Optimization-----------------------------------"); //Console.WriteLine(); //double[,] tableau = new double[,] //{ // { 0.0, -0.5, -3.0, -1.0, -4.0, }, // { 40.0, 1.0, 1.0, 1.0, 1.0, }, // { 10.0, -2.0, -1.0, 1.0, 1.0, }, // { 10.0, 0.0, 1.0, 0.0, -1.0, }, //}; //Console.WriteLine(" tableau (double): "); //ConsoleWrite(tableau); Console.WriteLine(); //Vector<double> simplex_result = LinearAlgebra.Simplex(ref tableau); //Console.WriteLine(" simplex(tableau): "); //ConsoleWrite(tableau); Console.WriteLine(); //Console.WriteLine(" resulting maximization: "); //ConsoleWrite(simplex_result); #endregion #region Symbolics Console.WriteLine(" Symbolics---------------------------------------"); Console.WriteLine(); Expression <Func <double, double> > expression1 = (x) => 2 * (x / 7); var syntax1 = Symbolics <double> .Parse(expression1); Console.WriteLine(" Expression 1: " + syntax1.ToString()); Console.WriteLine(" Simplified: " + syntax1.Simplify().ToString()); Console.WriteLine(" Plugin(5): " + syntax1.Assign("x", 5).Simplify().ToString()); Expression <Func <double, double> > expression2 = (x) => 2 * x / 7; var syntax2 = Symbolics <double> .Parse(expression2); Console.WriteLine(" Expression 2: " + syntax2.ToString()); Console.WriteLine(" Simplified: " + syntax2.Simplify().ToString()); Console.WriteLine(" Plugin(5): " + syntax2.Assign("x", 5).Simplify().ToString()); Expression <Func <double, double> > expression3 = (x) => 2 - x + 7; var syntax3 = Symbolics <double> .Parse(expression3); Console.WriteLine(" Expression 3: " + syntax3.ToString()); Console.WriteLine(" Simplified: " + syntax3.Simplify().ToString()); Console.WriteLine(" Plugin(5): " + syntax3.Assign("x", 5).Simplify().ToString()); Expression <Func <double, double> > expression4 = (x) => 2 + (x - 7); var syntax4 = Symbolics <double> .Parse(expression4); Console.WriteLine(" Expression 4: " + syntax4.ToString()); Console.WriteLine(" Simplified: " + syntax4.Simplify().ToString()); Console.WriteLine(" Plugin(5): " + syntax3.Assign("x", 5).Simplify().ToString()); #endregion Console.WriteLine(); Console.WriteLine("================================================="); Console.WriteLine("Example Complete..."); Console.ReadLine(); }
private void EvalFloatValue(Compute compute, int stIdx, int lgt, float sign) { if (expChr[stIdx] == '$') { string label = new string(expChr, stIdx + 1, lgt - 1); if (label.Equals("rand", StringComparison.InvariantCultureIgnoreCase)) { compute.Push(0, STACK_RAND); } else { int idx; try { idx = int.Parse(label) - 1; } catch { compute.Push(0, STACK_NUM); return; } compute.Push(0, STACK_VARIABLE + idx); } } else { try { float idx = float.Parse(new string(expChr, stIdx, lgt)); compute.Push(idx * sign, STACK_NUM); } catch { compute.Push(0, STACK_NUM); } } }
public static void TestMath() { #region math stuffs Console.WriteLine("Negate: " + (Compute <int> .Negate(7) == -7)); Console.WriteLine("Add: " + (Compute <int> .Add(7, 7) == 14)); Console.WriteLine("Subtract: " + (Compute <int> .Subtract(14, 7) == 7)); Console.WriteLine("Multiply: " + (Compute <int> .Multiply(7, 7) == 49)); Console.WriteLine("Divide: " + (Compute <int> .Divide(14, 7) == 2)); Console.WriteLine("AbsoluteValue: " + (Compute <int> .AbsoluteValue(7) == 7 && Compute <int> .AbsoluteValue(-7) == 7)); Console.WriteLine("Clamp: " + (Compute <int> .Clamp(7, 6, 8) == 7)); Console.WriteLine("Maximum: " + (Compute <int> .Maximum((Step <int> step) => { step(1); step(2); step(3); }) == 3)); Console.WriteLine("Minimum: " + (Compute <int> .Minimum((Step <int> step) => { step(1); step(2); step(3); }) == 1)); Console.WriteLine("LessThan: " + (Compute <int> .LessThan(1, 2) == true && Compute <int> .LessThan(2, 1) == false)); Console.WriteLine("GreaterThan: " + (Compute <int> .GreaterThan(2, 1) == true && Compute <int> .GreaterThan(1, 2) == false)); Console.WriteLine("Compare: " + (Compute <int> .Compare(2, 1) == Comparison.Greater && Compute <int> .Compare(1, 2) == Comparison.Less && Compute <int> .Compare(1, 1) == Comparison.Equal)); Console.WriteLine("Equate: " + (Compute <int> .Equate(2, 1) == false && Compute <int> .Equate(1, 1) == true)); Console.WriteLine("EqualsLeniency: " + (Compute <int> .EqualsLeniency(2, 1, 1) == true && Compute <int> .EqualsLeniency(2, 1, 0) == false && Compute <int> .EqualsLeniency(1, 1, 0) == true)); #endregion }
public float Eval(string exp) { Compute compute = (Compute)CollectionUtils.Get(computes, exp); if (compute == null) { expChr = new char[exp.Length]; int ecIdx = 0; bool skip = false; StringBuilder buf = new StringBuilder(exp); int depth = 0; bool balance = true; char ch; for (int i = 0; i < buf.Length; i++) { ch = buf[i]; switch (ch) { case ' ': case '\n': skip = true; break; case ')': depth--; if (depth < 0) balance = false; break; case '(': depth++; break; } if (skip) { skip = false; } else { expChr[ecIdx] = ch; ecIdx++; } } if (depth != 0 || !balance) { return 0; } compute = new Compute(); EvalExp(compute, 0, ecIdx); CollectionUtils.Put(computes, exp, compute); } return compute.Calc(); }
public Niblack(double threshold) { this.Threshold = threshold; this.computeResult = (std, mean) => std * this.Threshold + mean; }