/// <summary> /// 添加函数 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { using (frmAddFunction frmaddf = new frmAddFunction()) { frmaddf.Function = textBox1.Text; if (frmaddf.ShowDialog() == System.Windows.Forms.DialogResult.OK) { textBox1.Text = frmaddf.Function; //一元 if (textBox1.Text.ToLower().Contains('x') && !textBox1.Text.ToLower().Contains('y') && !textBox1.Text.ToLower().Contains('z')) { UnaryFunction func = (new SyntaxManager().ParseUnaryFunction(textBox1.Text)); unaryFunctionDrawingBoard1.Function = func; tabControl1.SelectedIndex = 0; } //二元 else if (textBox1.Text.ToLower().Contains('x') && textBox1.Text.ToLower().Contains('y') && !textBox1.Text.ToLower().Contains('z')) { BinaryFunction func = (new SyntaxManager().ParseBinaryFunction(textBox1.Text)); binaryFunctionDrawingBoard1.BinaryFunction = func; tabControl1.SelectedIndex = 1; } //三元 else { MultiFunction func = (new SyntaxManager().ParseMultiFunction(textBox1.Text)); MessageBox.Show("三元函数图像无法绘制!"); } } } }
static void Main(string[] args) { // ScalarFunction x = "x"; ScalarFunction y = "y"; ScalarFunction a = "a"; ScalarFunction b = "b"; ScalarFunction c = "c"; ScalarFunction d = "d"; ScalarFunction i = "i"; ScalarFunction j = "j"; MatrixFunction m = NewMatrix(new Matrix <ScalarFunction>( new[] { new ScalarFunction[] { a, b }, new ScalarFunction[] { c, d } })); VectorFunction v = NewColumnVector(new ScalarFunction[] { x, y }); VectorFunction r = NewColumnVector(new ScalarFunction[] { i, j }); BinaryFunction k = MatrixMethods.RotationMethod(m, v, r); k = k.Calculate(); //Console.WriteLine(((a * i + c * j) / (a * a + c * c)).Calculate()); //var sqrt = op_Exponentiation(op_Exponentiation(a, 2) + op_Exponentiation(c, 2), 0.5); //var d_y = ((a * j - c * i) / (a * d - c * b)) * (a * b + c * d); //var gg = ((x * (a * a + c * c)) + y) / sqrt == (a * i + c * j) / sqrt; //var gg2 = NewScalarFind(x, gg).Calculate(); //var gg3 = gg2.Calculate(NewScalarFind(y, y == d_y)); Console.ReadKey(); }
// Normal functions private static Value Transform(Value a, Value b, BinaryFunction accum, BinaryFunction f) { Value ret = new Value(a.Size); if (ret.Size == 0) { return(ret); } for (int i = 0; i < a.Size; ++i) { if (a.Size == b.Size) { ret[i] = f(a[i], b[i]); continue; } ret[i] = 0; for (int j = 0; j < b.Size; ++j) { if (j == 0) { ret[i] = f(a[i], b[j]); } else { ret[i] = accum(ret[i], f(a[i], b[j])); } } } return(ret); }
public static BinaryFunction <Arg1, Arg2, bool> Not2 <Arg1, Arg2>(BinaryFunction <Arg1, Arg2, bool> func) { return(delegate(Arg1 arg1, Arg2 arg2) { return !func(arg1, arg2); }); }
public Rule(IFuzzySet[] antecedent, IFuzzySet consequent, BinaryFunction tNorm, BinaryFunction implication) { this.antecedent = antecedent; this.consequent = consequent; this.tNorm = tNorm; this.implication = implication; }
static void Main() { DynamicMethod method = new DynamicMethod("MyFirst", null, null, typeof(Test)); ILGenerator gen = method.GetILGenerator(); gen.EmitWriteLine((string)"Hello World"); gen.Emit(OpCodes.Ret); method.Invoke(null, null); // Now use delegates DynamicMethod method2 = new DynamicMethod("MySecond", typeof(int), new[] { typeof(int), typeof(int) }, typeof(void)); ILGenerator gen2 = method2.GetILGenerator(); // Put arguments onto evaluation stack gen2.Emit(OpCodes.Ldarg_0); gen2.Emit(OpCodes.Ldarg_1); gen2.Emit(OpCodes.Add); gen2.Emit(OpCodes.Ret); BinaryFunction f2 = (BinaryFunction)method2.CreateDelegate(typeof(BinaryFunction)); Console.WriteLine("Using delegate: {0}", f2(1, 2)); // 3 int result = (int)method2.Invoke(null, new object[] { 2, 4 }); // Now invoke the dynamically generated method Console.WriteLine("Using delegate: {0}", f2(2, 6)); // 8 Console.WriteLine("Using delegate: {0}", f2(12, 8)); // 20 Console.WriteLine("Using delegate: {0}", f2(-12, 8)); // -4 // Using a delegate with 3 input parameters; compute n1*n2*n3 DynamicMethod method3 = new DynamicMethod("MyThird", typeof(int), new[] { typeof(int), typeof(int), typeof(int) }, typeof(void)); ILGenerator gen3 = method3.GetILGenerator(); // Put arguments onto evaluation stack gen3.Emit(OpCodes.Ldarg_0); gen3.Emit(OpCodes.Ldarg_1); gen3.Emit(OpCodes.Mul); gen3.Emit(OpCodes.Ldarg_2); gen3.Emit(OpCodes.Mul); gen3.Emit(OpCodes.Ret); TernaryFunction f3 = (TernaryFunction)method3.CreateDelegate(typeof(TernaryFunction)); Console.WriteLine("Using delegate: {0}", f3(1, 2, 2)); // 3 int result3 = (int)method3.Invoke(null, new object[] { 2, 4, 6 }); // Now invoke the dynamically generated method Console.WriteLine("Using delegate: {0}", f3(2, 6, 1)); // 12 Console.WriteLine("Using delegate: {0}", f3(12, 8, 2)); // 192 Console.WriteLine("Using delegate: {0}", f3(-12, 2, 2)); // -48 }
public Object ExecuteBinaryFunction(string id, BinaryFunction action, Object a, Object b, string pos) { // Called with two doubles if (a.GetType() == typeof(double) && b.GetType() == typeof(double)) { return(action((double)a, (double)b)); } // Called with a list and a double else if (a.GetType() == typeof(Object[]) && b.GetType() == typeof(double)) { Object[] list = (Object[])a; Object[] newList = new Object[list.Length]; for (int i = 0; i < list.Length; i++) { newList[i] = ExecuteBinaryFunction(id, action, list[i], b, pos); } return(newList); // Called with a double and a list } else if (a.GetType() == typeof(double) && b.GetType() == typeof(Object[])) { Object[] list = (Object[])b; Object[] newList = new Object[list.Length]; for (int i = 0; i < list.Length; i++) { newList[i] = ExecuteBinaryFunction(id, action, a, list[i], pos); } return(newList); // Called with two lists } else if (a.GetType() == typeof(Object[]) && b.GetType() == typeof(Object[])) { Object[] listA = (Object[])a; Object[] listB = (Object[])b; if (listA.Length != listB.Length) { throw new Exception(pos + "cannot apply " + id + " to lists of different length (got " + listA.Length + " and " + listB.Length + ")"); } Object[] newList = new Object[listA.Length]; for (int i = 0; i < listA.Length; i++) { newList[i] = ExecuteBinaryFunction(id, action, listA[i], listB[i], pos); } return(newList); // Called with something else } else { throw new Exception(pos + "cannot apply " + id + " to variables of type " + a.GetType().ToString() + " and " + b.GetType().ToString()); } }
// Randomizes the ViewOrder of all the enabled, unplayed/playing songs public void Shuffle() { if (!Populate) { if (current_track == null) { return; } int enabled_count = EnabledCount; int first_view_order = (int)CurrentTrackViewOrder; int last_view_order = first_view_order + enabled_count; // If the current track is playing, don't shuffle it if (ServiceManager.PlayerEngine.IsPlaying(current_track)) { first_view_order++; } // Nothing to do if less than 2 tracks if (last_view_order - first_view_order < 2) { return; } // Save the current_track index, so we can update the current track // to be whatever one is at that position after we shuffle them -- assuming // the current_track isn't already playing. int current_index = TrackModel.IndexOf(current_track); // Setup a function that will return a random ViewOrder in the range we want var rand = new Random(); var func_id = "play-queue-shuffle-order-" + rand.NextDouble().ToString(); var view_orders = Enumerable.Range(first_view_order, last_view_order) .OrderBy(a => rand.NextDouble()) .ToList(); int i = 0; BinaryFunction.Add(func_id, (f, b) => view_orders[i++]); ServiceManager.DbConnection.Execute( "UPDATE CorePlaylistEntries SET ViewOrder = HYENA_BINARY_FUNCTION (?, NULL, NULL) WHERE PlaylistID = ? AND ViewOrder >= ?", func_id, DbId, first_view_order ); BinaryFunction.Remove(func_id); Reload(); // Update the current track unless it was playing (and therefore wasn't moved) if (!ServiceManager.PlayerEngine.IsPlaying(current_track)) { SetCurrentTrack(TrackModel[current_index] as DatabaseTrackInfo); } } }
public void RotateMethod() { MatrixFunction m = NewMatrix(new Matrix <ScalarFunction>( new[] { new ScalarFunction[] { "a", "b" }, new ScalarFunction[] { "c", "d" } })); VectorFunction v = NewColumnVector(new ScalarFunction[] { "x", "y" }); VectorFunction r = NewColumnVector(new ScalarFunction[] { "i", "j" }); BinaryFunction b = MatrixMethods.RotationMethod(m, v, r); }
public static IFuzzySet BinaryOperation(IFuzzySet set1, IFuzzySet set2, BinaryFunction function) { var result = new MutableFuzzySet(set1.GetDomain()); foreach (var element in set1.GetDomain()) { var x = set1.GetValueAt(element); var y = set2.GetValueAt(element); result.Set(element, function(x, y)); } return(result); }
public AlbumDuplicateSolver() { Id = "dupe-album"; Name = Catalog.GetString("Duplicate Albums"); Description = Catalog.GetString("Displayed are albums that should likely be merged. For each row, click the desired title to make it bold, or uncheck it to take no action."); AddFinder( "Title", "AlbumID", "CoreAlbums, CoreArtists", "CoreAlbums.ArtistID = CoreArtists.ArtistID AND Title IS NOT NULL AND Name IS NOT NULL AND " + String.Format("AlbumID IN (SELECT DISTINCT(AlbumID) FROM CoreTracks WHERE PrimarySourceID = {0})", ServiceManager.SourceManager.MusicLibrary.DbId), "HYENA_BINARY_FUNCTION ('dupe-album', Title, Name)" ); BinaryFunction.Add(Id, NormalizedGroup); }
static void Main(string[] args) { var dynMeth = new DynamicMethod("Foo", null, null, typeof(Program)); ILGenerator gen = dynMeth.GetILGenerator(); gen.EmitWriteLine("Hello World"); gen.Emit(OpCodes.Ret); dynMeth.Invoke(null, null); dynMeth = new DynamicMethod("Foo", null, null, typeof(Program)); gen = dynMeth.GetILGenerator(); MethodInfo privateMethod = typeof(Program).GetMethod("HelloWorld", BindingFlags.NonPublic | BindingFlags.Static); gen.Emit(OpCodes.Call, privateMethod); gen.Emit(OpCodes.Ret); dynMeth.Invoke(null, null); dynMeth = new DynamicMethod("Foo", null, null, typeof(Program)); gen = dynMeth.GetILGenerator(); MethodInfo WriteLineInt = typeof(Console).GetMethod("WriteLine", new Type[] { typeof(int) }); gen.Emit(OpCodes.Ldc_I4, 123); gen.Emit(OpCodes.Ldc_I4, 123); gen.Emit(OpCodes.Add); gen.Emit(OpCodes.Call, WriteLineInt); gen.Emit(OpCodes.Ret); dynMeth.Invoke(null, null); dynMeth = new DynamicMethod("Foo", typeof(int), // Return type = int new[] { typeof(int), typeof(int) }, // Parameter types = int, int typeof(void)); gen = dynMeth.GetILGenerator(); gen.Emit(OpCodes.Ldarg_0); // Push first arg onto eval stack gen.Emit(OpCodes.Ldarg_1); // Push second arg onto eval stack gen.Emit(OpCodes.Add); // Add them together (result on stack) gen.Emit(OpCodes.Ret); // Return with stack having 1 value BinaryFunction f1 = (BinaryFunction)dynMeth.CreateDelegate(typeof(BinaryFunction)); Func <int, int, int> f2 = (Func <int, int, int>)dynMeth.CreateDelegate(typeof(Func <int, int, int>)); int result = (int)dynMeth.Invoke(null, new object[] { 123, 123 }); Console.WriteLine(result); Console.WriteLine(f1(123, 124)); Console.WriteLine(f2(123, 125)); }
public ArtistDuplicateSolver() { Id = "dupe-artist"; Name = Catalog.GetString("Duplicate Artists"); Description = Catalog.GetString("Displayed are artists that should likely be merged. For each row, click the desired name to make it bold, or uncheck it to take no action."); AddFinder( "Name", "ArtistID", "CoreArtists", String.Format( @"(Name IS NOT NULL AND ArtistID IN (SELECT DISTINCT(ArtistID) FROM CoreTracks WHERE PrimarySourceID = {0}) OR ArtistID IN (SELECT DISTINCT(a.ArtistID) FROM CoreTracks t, CoreAlbums a WHERE t.AlbumID = a.AlbumID AND t.PrimarySourceID = {0}))", EnableUnitTests ? 0 : ServiceManager.SourceManager.MusicLibrary.DbId ), "HYENA_BINARY_FUNCTION ('dupe-artist', Name, NULL)" ); BinaryFunction.Add(Id, NormalizeArtistName); }
public GenreDuplicateSolver() { Id = "dupe-genre"; Name = Catalog.GetString("Duplicate Genres"); Description = Catalog.GetString("Displayed are genres that should likely be merged. For each row, click the desired genre to make it bold, or uncheck it to take no action."); AddFinder( "Genre", "TrackID", "CoreTracks", String.Format(@" TrackID IN (SELECT TrackID FROM CoreTracks WHERE PrimarySourceID = {0} GROUP BY Genre ) AND Genre IS NOT NULL", ServiceManager.SourceManager.MusicLibrary.DbId ), "HYENA_BINARY_FUNCTION ('dupe-genre', Genre, NULL)" ); BinaryFunction.Add(Id, NormalizedGroup); }
private static double Accumulate(Value[] vals, BinaryFunction f) { bool first = true; double ret = 0; ForallValues(vals, (v) => { if (first) { ret = v; } else { ret = f(ret, v); } first = false; }); return(ret); }
public static List <Pixel2> FindStabilityExtremums(double[,] data, double sigmaFactor, BinaryFunction predicate) { List <Pixel2> result = new List <Pixel2>(); bool[,] region = FindStabilityRegion(data, sigmaFactor, predicate); for (; ;) { int row = -1; int column = -1; bool status = NumericalMethods.FindConditionalExtremum(data, region, predicate, out row, out column); if (!status) { break; } result.Add(new Pixel2(column, row)); region = Morphology.Erosion(region, row, column); } return(result); }
/// <summary> /// The method looks for a stability region. /// threshold value = limitValue + sigmaCoefficient * sigma; /// </summary> /// <param name="data">can't be null</param> /// <param name="limitValue"></param> /// <param name="sigmaCoefficient">defines filter amplitude and direction; see threshold value calculation</param> /// <returns> /// true cells defines stability region /// false cells defines instability region /// </returns> public static bool[,] FindStabilityRegion(double[,] data, double sigmaFactor, BinaryFunction predicate, double limitValue = 1) { int rows = data.GetLength(0); int columns = data.GetLength(1); List <double> deviations = new List <double>(); for (int row = 0; row < rows; ++row) { for (int column = 0; column < columns; ++column) { double value = data[row, column]; if (row - 1 >= 0) { double delta = data[row - 1, column] - value; deviations.Add(delta); } if (row < rows - 1) { double delta = data[row + 1, column] - value; deviations.Add(delta); } if (column - 1 >= 0) { double delta = data[row, column - 1] - value; deviations.Add(delta); } if (column < columns - 1) { double delta = data[row, column + 1] - value; deviations.Add(delta); } } } double sigma = Statistics.CalculateSampleVariance(deviations.ToArray()); sigma = NumericalMethods.Sqrt(sigma); sigma *= sigmaFactor; double threshold = predicate(1, 0) ? (limitValue - sigma) : (limitValue + sigma); bool[,] result = new bool[rows, columns]; for (int row = 0; row < rows; ++row) { for (int column = 0; column < columns; ++column) { result[row, column] = predicate(data[row, column], threshold); } } double ry = NumericalMethods.Sqrt(rows); double rx = NumericalMethods.Sqrt(columns); int r = (int)Math.Min(rx, ry) - 1; for (int index = 0; index < r; ++index) { result = Morphology.Erosion(result); } return(result); }
public static UnaryFunction <Arg, Result> Bind1st <Arg, Result>(BinaryFunction <Arg, Arg, Result> func, Arg arg1) { return(new Binder1st <Arg, Arg, Result>(func, arg1).Execute); }
private static Value Transform(Value a, Value b, BinaryFunction f) { return(Transform(a, b, (la, lb) => la + lb, f)); }
public static UnaryFunction <Arg, Result> Bind2nd <Arg, Result>(BinaryFunction <Arg, Arg, Result> func, Arg arg2) { return(new Binder2nd <Arg, Arg, Result>(func, arg2).Execute); }
public override void Dispose() { base.Dispose(); BinaryFunction.Remove(Id); }
public Expression AddBinaryFunction(string Name, Expression TypeA, Expression TypeB, Expression ReturnType, BinaryFunction Handler) { return this.AddRootVariable(Name, Expression.FunctionType(this.NextFreeIndex, Expression.Tuple(TypeA, TypeB), ReturnType), new BinaryFunctionValue() { Function = Handler }); }
private Variable ApplyBinaryFunction(Variable a, Variable b, BinaryFunction action) { if(a.type == VarType.NUMBER && b.type == VarType.NUMBER) return new Variable("", VarType.NUMBER, action(a.val, b.val)); else if(a.type == VarType.NUMBER && b.type == VarType.LIST) { List<Variable> newElements = new List<Variable>(b.elements.Count); foreach(Variable e in b.elements) newElements.Add(ApplyBinaryFunction(a, e, action)); return new Variable("", VarType.LIST, newElements); } else if(a.type == VarType.LIST && b.type == VarType.NUMBER) { List<Variable> newElements = new List<Variable>(a.elements.Count); foreach(Variable e in a.elements) newElements.Add(ApplyBinaryFunction(e, b, action)); return new Variable("", VarType.LIST, newElements); } else if(a.type == VarType.LIST && b.type == VarType.LIST) { if(a.elements.Count != b.elements.Count) throw new Exception("Trying to perform a binary operation on lists of unequal size."); List<Variable> newElements = new List<Variable>(a.elements.Count); for(int i=0; i<a.elements.Count; i++) newElements.Add(ApplyBinaryFunction(a.elements[i], b.elements[i], action)); return new Variable("", VarType.LIST, newElements); } throw new Exception("Trying to perform an operation on invalid types."); }
public Binder1st(BinaryFunction <Arg1, Arg2, Result> func, Arg1 arg1) { m_Arg1 = arg1; m_Function = func; }
//How the value of an AutoExpression is decided //If the AutoExpression is the parameter to a higher order function // - Return the input //If we are inside a higher-order function // - The 'parameter variables' are 斯,成,它,感,干,法 // - They are placed upon a stack // - Based on how many is needed, that number is popped from the stack // - E.g some higher-order functions require 3 parameters, some only need 2 or 1 // - If there are at least two parameter variables, the first one will be designated as the first autofill // - and the second will be designated as the second autofill //Else if we are not inside a higher-order function // - The first autofill will be the first input passed to the program // - The second autofill will be the second input passed to the program //Now we have our first and second autofill // - If there are zero autofill, just use 0 // - If there is only one autofill, use that one autofill // - If there are at least two autofills defined: // - If the expression is an argument to a function, use the first autofill // - Use the second autofill // - Else just use the first VObject Evaluate(Expression ast) { switch (ast) { //Self-explanatory case NumericLiteralExpression number: return(new VObject(number.Value)); case StringLiteralExpression str: return(new VObject(str.Value)); case VariableReferenceExpression variable: return(programState.Variables[variable.Name]); case ConditionalExpression conditional: if (Evaluate(conditional.Condition).IsTruthy()) { return(Evaluate(conditional.TrueExpression)); } else { return(Evaluate(conditional.FalseExpression)); } //Use the first input as autofill by default case AutoExpression _: return(programState.Autofill_1); case FunctionInvocationExpression funcExpr: VObject caller; if (funcExpr.Caller is AutoExpression) { caller = programState.Autofill_1; } else { caller = Evaluate(funcExpr.Caller); } if (Function.IsHigherOrder(funcExpr.Function, caller.ObjectType)) { HigherOrderFunction func = (HigherOrderFunction)Function.Get(funcExpr.Function, caller.ObjectType); Lambda lambda; bool createdLambda = false; // If an autoexpression is submitted as a lambda, then either use the default lambda or if not available, a lambda that returns the first input if (funcExpr.Argument is AutoExpression) { lambda = func.DefaultLambda ?? (x => x[0]); } else { lambda = CreateLambda(funcExpr.Argument, func.LambdaParameters); createdLambda = true; } //We pass the lambda that we created into the function var res = func.Invoke(caller, lambda); //Re-rotate the parameter variables back //We rotated them in the CreateLambda method //Note this only triggers if CreateLambda was called if (createdLambda) { for (int i = 0; i < PARAMETER_VARIABLES.Length - func.LambdaParameters; i++) { ParamVars.Enqueue(ParamVars.Dequeue()); } } return(res); } if (Function.IsUnary(funcExpr.Function)) { UnaryFunction func = (UnaryFunction)Function.Get(funcExpr.Function, caller.ObjectType); if (func is UnaryFunctionWithProgramState funcWithProgState) { return(funcWithProgState.Invoke(caller, programState)); } else { return(func.Invoke(caller)); } } else { VObject arg = funcExpr.Argument is AutoExpression ? programState.Autofill_2 : Evaluate(funcExpr.Argument); BinaryFunction func = (BinaryFunction)Function.Get(funcExpr.Function, caller.ObjectType, arg.ObjectType); return(func.Invoke(caller, arg)); } throw new Exception(); case InterpolatedStringExpression intpStr: return(string.Concat(intpStr.Expressions.Select(x => Evaluate(x).ToString()))); default: ErrorHandler.InternalError("This shouldn't happen."); throw new Exception(); } }
public static UnaryFunction <T, T> Bind2nd <T>(BinaryFunction <T, T, T> func, T arg2) { return(new Binder2nd <T, T, T>(func, arg2).Execute); }
public Binder2nd(BinaryFunction <Arg1, Arg2, Result> func, Arg2 arg2) { m_Arg2 = arg2; m_Function = func; }
public Binary(BinaryFunction func, Function inner0, Function inner1) { this.func = func; this.inner0 = inner0; this.inner1 = inner1; }
private static double Accumulate(Value vals, BinaryFunction f) { return(Accumulate(new Value[] { vals }, f)); }
public static UnaryFunction <T, T> Bind1st <T>(BinaryFunction <T, T, T> func, T arg1) { return(new Binder1st <T, T, T>(func, arg1).Execute); }
public static bool FindConditionalExtremum(double[,] data, bool[,] condition, BinaryFunction predicate, out int row, out int column) { if (null == data) { throw new NullReferenceException("data cannot be null"); } if (null == condition) { throw new NullReferenceException("condition cannot be null"); } int rows = data.GetLength(0); int columns = data.GetLength(1); if ((rows != condition.GetLength(0)) || (columns != condition.GetLength(1))) { throw new ArgumentException("data and condition have different sizes"); } row = -1; column = -1; bool result = false; double extremum = predicate(1, 0) ? double.NegativeInfinity : double.PositiveInfinity; for (int r = 0; r < rows; ++r) { for (int c = 0; c < columns; ++c) { if (!condition[r, c]) { continue; } double value = data[r, c]; if (predicate(value, extremum)) { extremum = value; row = r; column = c; result = true; } } } return(result); }
public BinaryOperator(string token, BinaryFunction function, Precedence precedence, bool leftAssociative = true) : base(token, (c, ctx) => function(c[0].Eval(ctx), c[1].Eval(ctx)), 2, precedence, leftAssociative) { }