示例#1
0
        public void SparseSample_ComplexFloat_Identity()
        {
            NumericsConfiguration.NativeProviderPath = @"C:\Program Files (x86)\Extreme Optimization\Numerical Libraries for .NET\bin\Net40";
            NumericsConfiguration.Providers.RegisterSinglePrecisionProvider();
            NumericsConfiguration.AutoLoadNativeProviders = true;
            CoreImplementations <float> .UseNative();

            Console.WriteLine(CoreImplementations <Complex <float> > .LinearAlgebra.Name);

            SparseCompressedColumnMatrix <Complex <float> > matrixA = Matrix.CreateSparse <Complex <float> >(3, 3);

            matrixA.SetValue(new Complex <float>(1, 0), 0, 0);
            matrixA.SetValue(new Complex <float>(1, 0), 1, 1);
            matrixA.SetValue(new Complex <float>(1, 0), 2, 2);
            Vector <Complex <float> > vectorB = Vector.Create(new Complex <float>(1.0f, 0), new Complex <float>(2.0f, 0), new Complex <float>(3.0f, 0));

            IterativeSparseSolver <Complex <float> > solver       = new BiConjugateGradientSolver <Complex <float> >(matrixA);
            DenseVector <Complex <float> >           resultVector = solver.Solve(vectorB);

            Console.WriteLine("Result: {0}", resultVector);
            Console.WriteLine("Solved in {0} iterations.", solver.IterationsNeeded);
            Console.WriteLine("Estimated error: {0}", solver.SolutionReport.Error);

            // With incomplete LU preconditioner
            solver.Preconditioner = new IncompleteLUPreconditioner <Complex <float> >(matrixA);
            resultVector          = solver.Solve(vectorB);

            Console.WriteLine("Result: {0}", resultVector);
            Console.WriteLine("Solved in {0} iterations.", solver.IterationsNeeded);
            Console.WriteLine("Estimated error: {0}", solver.EstimatedError);
        }
示例#2
0
 public APad ProcessClick(int logicalX, int logicalY)
 {
     if (LastCommand.IsOneOf(CommandType.Continue, CommandType.WaitClick))
     {
         return(From(Program, Exp.Call(Program, Memory.ToExp(), CoreImplementations.Pair(logicalX, logicalY))));
     }
     throw new InvalidOperationException(LastCommand.ToString());
 }
示例#3
0
 public static Exp ToExp(this Data?data)
 {
     return(data switch
     {
         null => CoreImplementations.emptyList,
         NumData n => n.Value,
         PairData pair => CoreImplementations.Pair(pair.Value.ToExp(), pair.Next.ToExp()),
         _ => throw new NotSupportedException($"{data}")
     });
示例#4
0
        public void ExecuteSample()
        {
            // The line below sets the path where the native assemblies
            // are located. The "XO_LIBRARY_PATH" environment variable
            // points here, too.
            NumericsConfiguration.NativeProviderPath =
                @"C:\Program Files (x86)\Extreme Optimization\Numerical Libraries for .NET\bin\Net40";

            // Register the single precision providers.
            NumericsConfiguration.Providers.RegisterSinglePrecisionProvider();
            NumericsConfiguration.AutoLoadNativeProviders = true;
            CoreImplementations <float> .UseNative();

            // Which provider are we using?
            Console.WriteLine(CoreImplementations <Complex <float> > .LinearAlgebra.Name);

            int N = 228724; // size
            int K = 96;     // non-zeros per column

            // Create some random matrices. Code is below.
            // Use a seed so we can reproduce the same values.
            NumericsConfiguration.DefaultRandomNumberGenerator = new Extreme.Mathematics.Random.MersenneTwister(117);

            var matrixA = CreateSparseRandom(N, K);
            var vectorB = CreateRandom(N);// CreateRandom(N);

            // Now run the solver with and without preconditioner:
            var sw     = Stopwatch.StartNew();
            var solver = new BiConjugateGradientSolver <Complex <float> >(matrixA);

            Console.WriteLine("Starting solve...");
            Vector <Complex <float> > resultVector;

            resultVector = solver.Solve(vectorB);
            sw.Stop();

            Console.WriteLine("Result: {0}", resultVector.GetSlice(0, 10));
            Console.WriteLine("Solved in {0} iterations.", solver.IterationsNeeded);
            Console.WriteLine("Estimated error: {0}", solver.SolutionReport.Error);
            Console.WriteLine("Total time: {0} s", sw.Elapsed.TotalSeconds);

            // With incomplete LU preconditioner
            sw.Restart();
            solver.Preconditioner = new IncompleteLUPreconditioner <Complex <float> >(matrixA);
            resultVector          = solver.Solve(vectorB);
            sw.Stop();

            Console.WriteLine("Result: {0}", resultVector.GetSlice(0, 10));
            Console.WriteLine("Solved in {0} iterations.", solver.IterationsNeeded);
            Console.WriteLine("Estimated error: {0}", solver.EstimatedError);
            Console.WriteLine("Total time: {0} s", sw.Elapsed.TotalSeconds);

            Console.WriteLine("Press any key to exit.");
            Console.ReadLine();
        }
        public static void RenderPages(string messageFilename, int scale, bool withWav, string outputDir)
        {
            if (!Directory.Exists(outputDir))
            {
                Directory.CreateDirectory(outputDir);
            }
            var messageDir = Path.GetDirectoryName(messageFilename) !;
            var message    = File.ReadAllText(messageFilename);
            var pages      = message.Replace("\r", "").Split("\n\n");

            for (int i = 0; i < pages.Length; i++)
            {
                var renderer   = new RenderContext(Renderer.Instance);
                var lines      = pages[i].Split("\n");
                var needBorder = false;
                foreach (var line in lines)
                {
                    try
                    {
                        if (line.StartsWith("//"))
                        {
                            continue;
                        }
                        if (line.StartsWith("IMAGE_"))
                        {
                            var imageName = line.Split("_", 2)[1];
                            using var stream = new FileStream(Path.Combine(messageDir, imageName), FileMode.Open);
                            var pixels = CoreImplementations.ImageToPixels(stream);
                            renderer.AddPixels(pixels);
                        }
                        else
                        {
                            ReportIncorrectMessagesToConsole(line);
                            needBorder = true;
                            renderer.AddLine(line);
                        }
                    }
                    catch (Exception e)
                    {
                        throw new Exception(line, e);
                    }
                }
                if (renderer.Points.Count == 0)
                {
                    throw new Exception(i.ToString());
                }
                var humanReadableIndex = i + 1;
                var points             = needBorder ? AddBorder(renderer.Points.ToList()).ToList() : renderer.Points;
                SaveImageFile(scale, points, Path.Combine(outputDir, $"message{humanReadableIndex}.png"));
                if (withWav && i == 0)
                {
                    SaveAudioFile(points, Path.Combine(outputDir, $"message{humanReadableIndex}.wav"));
                }
            }
        }
示例#6
0
 public static APad Boot(Exp prog)
 {
     return(From(prog, Exp.Call(prog, CoreImplementations.emptyList, CoreImplementations.Pair(0, 0))));
 }
示例#7
0
 private static Exp RegisterAndUseImage(string symbolName, CompilationContext context)
 {
     return(CoreImplementations.BitEncodeSymbolByName(symbolName));
 }
示例#8
0
        public static Exp CompileExpression(ExpressionSyntax expression, CompilationContext context)
        {
            switch (expression)
            {
            case LiteralExpressionSyntax literal when literal.IsKind(SyntaxKind.StringLiteralExpression):
                return(RegisterAndUseImage((string)literal.Token.Value !, context));

            case LiteralExpressionSyntax literal when literal.IsKind(SyntaxKind.NumericLiteralExpression):
                return(literal.Token.Value !is int?new Num((int)literal.Token.Value !) : new Num((long)literal.Token.Value !));

            case LiteralExpressionSyntax literal when literal.IsKind(SyntaxKind.TrueLiteralExpression):
                return(CoreImplementations.True);

            case LiteralExpressionSyntax literal when literal.IsKind(SyntaxKind.FalseLiteralExpression):
                return(CoreImplementations.False);

            case LiteralExpressionSyntax literal when literal.IsKind(SyntaxKind.NullLiteralExpression):
                return(CoreImplementations.emptyList);

            case SimpleNameSyntax id:
                return(GetFunction(id, context));

            case BinaryExpressionSyntax bin when bin.IsKind(SyntaxKind.EqualsExpression) && bin.Right.IsKind(SyntaxKind.NullLiteralExpression):
                return(CoreImplementations.isEmptyList.Call(CompileExpression(bin.Left, context)));

            case BinaryExpressionSyntax bin when bin.IsKind(SyntaxKind.NotEqualsExpression) && bin.Right.IsKind(SyntaxKind.NullLiteralExpression):
                return(CoreImplementations.not.Call(CoreImplementations.isEmptyList.Call(CompileExpression(bin.Left, context))));

            case BinaryExpressionSyntax bin:
            {
                var left  = CompileExpression(bin.Left, context);
                var right = CompileExpression(bin.Right, context);
                if (bin.IsKind(SyntaxKind.AddExpression))
                {
                    return(left + right);
                }
                if (bin.IsKind(SyntaxKind.MultiplyExpression))
                {
                    return(left * right);
                }
                if (bin.IsKind(SyntaxKind.SubtractExpression))
                {
                    return(-right + left);
                }
                if (bin.IsKind(SyntaxKind.DivideExpression))
                {
                    return(left / right);
                }
                if (bin.IsKind(SyntaxKind.ModuloExpression))
                {
                    return(left % right);
                }
                if (bin.IsKind(SyntaxKind.LessThanExpression))
                {
                    return(left < right);
                }
                if (bin.IsKind(SyntaxKind.GreaterThanExpression))
                {
                    return(left > right);
                }
                if (bin.IsKind(SyntaxKind.LessThanOrEqualExpression))
                {
                    return(left <= right);
                }
                if (bin.IsKind(SyntaxKind.GreaterThanOrEqualExpression))
                {
                    return(left >= right);
                }
                if (bin.IsKind(SyntaxKind.EqualsExpression))
                {
                    return(right == left);
                }
                if (bin.IsKind(SyntaxKind.NotEqualsExpression))
                {
                    return(left != right);
                }
                if (bin.IsKind(SyntaxKind.LogicalAndExpression))
                {
                    return(left & right);
                }
                if (bin.IsKind(SyntaxKind.LogicalOrExpression))
                {
                    return(left | right);
                }
                break;
            }

            case PrefixUnaryExpressionSyntax prefixUnary:
            {
                var val = CompileExpression(prefixUnary.Operand, context);
                if (prefixUnary.IsKind(SyntaxKind.UnaryMinusExpression))
                {
                    return(CoreImplementations.negate.Call(val));
                }
                if (prefixUnary.IsKind(SyntaxKind.LogicalNotExpression))
                {
                    return(CoreImplementations.not.Call(val));
                }
                break;
            }

            case ParenthesizedExpressionSyntax paren:
                return(CompileExpression(paren.Expression, context));

            case ConditionalExpressionSyntax cond:
                return(CoreImplementations.If(
                           CompileExpression(cond.Condition, context),
                           CompileExpression(cond.WhenTrue, context),
                           CompileExpression(cond.WhenFalse, context)));

            case InvocationExpressionSyntax inv:
            {
                var argsSyn = inv.ArgumentList.Arguments.Select(a => a.Expression).ToArray();
                if (inv.Expression is MemberAccessExpressionSyntax memberAccess)
                {
                    // call as method (smth.F(...))
                    var isExtensionMethod = !(context.SemanticModel.GetSymbolInfo(memberAccess.Expression).Symbol is ITypeSymbol);
                    var arguments         = isExtensionMethod ? argsSyn.Prepend(memberAccess.Expression).ToArray() : argsSyn;
                    var funcName          = memberAccess.Name.Identifier.Text;
                    var res = TryCompileSpecialFunctions(funcName, arguments, context);
                    if (!(res is null))
                    {
                        return(res);
                    }
                    // Call as static method Core.Pair(a, b)
                    var func = GetFunction(memberAccess, context);
                    return(CreateFunCall(func, arguments, context));
                }
                // Call as simple function f(x)
                else if (inv.Expression is SimpleNameSyntax nameSyntax)
                {
                    var res = TryCompileSpecialFunctions(nameSyntax.Identifier.Text, argsSyn, context);
                    if (!(res is null))
                    {
                        return(res);
                    }
                }
                return(CreateFunCall(CompileExpression(inv.Expression, context), argsSyn, context));
            }

            case SimpleLambdaExpressionSyntax simpleLambda:
            {
                var body =
                    simpleLambda.ExpressionBody != null
                                ? CompileExpression(simpleLambda.ExpressionBody !, context)
                                : CompileBlock(simpleLambda.Block !.Statements, 0, context);

                return(Exp.Lambda(simpleLambda.Parameter.Identifier.Text, body));
            }

            case ParenthesizedLambdaExpressionSyntax parenLambda:
            {
                var body =
                    parenLambda.ExpressionBody != null
                                ? CompileExpression(parenLambda.ExpressionBody !, context)
                                : CompileBlock(parenLambda.Block !.Statements, 0, context);

                var vars = parenLambda.ParameterList.Parameters.Select(p => p.Identifier.Text);
                return(Exp.Lambda(vars, body));
            }

            case CastExpressionSyntax cast:
                return(CompileExpression(cast.Expression, context));

            case ImplicitArrayCreationExpressionSyntax impArray:
                var values = impArray.Initializer.Expressions.Reverse().Select(expression1 => CompileExpression(expression1, context));
                return(values.Aggregate(CoreImplementations.emptyList, (res, v) => new Pair(v, res)));

            case ArrayCreationExpressionSyntax array:
                return(array.Initializer !
                       .Expressions
                       .Reverse()
                       .Aggregate(
                           CoreImplementations.emptyList,
                           (res, v) => new Pair(CompileExpression(v, context), res)));

            case MemberAccessExpressionSyntax memberAccess:
                return(CompileMemberAccess(memberAccess, context));

            case TupleExpressionSyntax tuple:
                return(CoreImplementations.Tuple(tuple.Arguments.Select(a => CompileExpression(a.Expression, context)).ToArray()));

            case ObjectCreationExpressionSyntax objCreation:
                return(CoreImplementations.List(objCreation.ArgumentList !.Arguments.Select(a => CompileExpression(a.Expression, context)).ToArray()));
            }
            throw new NotSupportedException($"{expression}: {expression.GetType()} {expression.Kind()}");
        }