コード例 #1
0
ファイル: Emit.cs プロジェクト: csainty/Sigil
        /// <summary>
        /// Writes the CIL stream out to the MethodBuilder used to create this Emit.
        ///
        /// Validation that cannot be run until a method is finished is run, and various instructions
        /// are re-written to choose "optimal" forms (Br may become Br_S, for example).
        ///
        /// Once this method is called the Emit may no longer be modified.
        ///
        /// Returns a MethodBuilder, which can be used to define overrides or for further inspection.
        ///
        /// `instructions` will be set to a representation of the instructions making up the returned method.
        /// Note that this string is typically *not* enough to regenerate the method, it is available for
        /// debugging purposes only.  Consumers may find it useful to log the instruction stream in case
        /// the returned method fails validation (indicative of a bug in Sigil) or
        /// behaves unexpectedly (indicative of a logic bug in the consumer code).
        /// </summary>
        public MethodBuilder CreateMethod(out string instructions, OptimizationOptions optimizationOptions = OptimizationOptions.All)
        {
            if (MtdBuilder == null)
            {
                throw new InvalidOperationException("Emit was not created to build a method, thus CreateMethod cannot be called");
            }

            if (MethodBuilt)
            {
                instructions = null;
                return(MtdBuilder);
            }

            Seal(optimizationOptions);

            MethodBuilt = true;

            var il = MtdBuilder.GetILGenerator();

            instructions = IL.UnBuffer(il);

            AutoNamer.Release(this);

            return(MtdBuilder);
        }
コード例 #2
0
ファイル: Emit.cs プロジェクト: csainty/Sigil
        /// <summary>
        /// Writes the CIL stream out to the ConstructorBuilder used to create this Emit.
        ///
        /// Validation that cannot be run until a method is finished is run, and various instructions
        /// are re-written to choose "optimal" forms (Br may become Br_S, for example).
        ///
        /// Once this method is called the Emit may no longer be modified.
        ///
        /// Returns a ConstructorBuilder, which can be used to define overrides or for further inspection.
        ///
        /// `instructions` will be set to a representation of the instructions making up the returned constructor.
        /// Note that this string is typically *not* enough to regenerate the constructor, it is available for
        /// debugging purposes only.  Consumers may find it useful to log the instruction stream in case
        /// the returned constructor fails validation (indicative of a bug in Sigil) or
        /// behaves unexpectedly (indicative of a logic bug in the consumer code).
        /// </summary>
        public ConstructorBuilder CreateConstructor(out string instructions, OptimizationOptions optimizationOptions = OptimizationOptions.All)
        {
            if (ConstrBuilder == null)
            {
                throw new InvalidOperationException("Emit was not created to build a constructor, thus CreateConstructor cannot be called");
            }

            if (ConstructorBuilt)
            {
                instructions = null;
                return(ConstrBuilder);
            }

            ConstructorBuilt = true;

            Seal(optimizationOptions);

            var il = ConstrBuilder.GetILGenerator();

            instructions = IL.UnBuffer(il);

            AutoNamer.Release(this);

            return(ConstrBuilder);
        }
コード例 #3
0
ファイル: Emit.cs プロジェクト: arlm/Sigil-vNext
        /// <summary>
        /// Converts the CIL stream into a delegate.
        ///
        /// Validation that cannot be run until a method is finished is run, and various instructions
        /// are re-written to choose "optimal" forms (Br may become Br_S, for example).
        ///
        /// Once this method is called the Emit may no longer be modified.
        ///
        /// `instructions` will be set to a representation of the instructions making up the returned delegate.
        /// Note that this string is typically *not* enough to regenerate the delegate, it is available for
        /// debugging purposes only.  Consumers may find it useful to log the instruction stream in case
        /// the returned delegate fails validation (indicative of a bug in Sigil) or
        /// behaves unexpectedly (indicative of a logic bug in the consumer code).
        /// </summary>
        public Delegate CreateDelegate(Type delegateType, out string instructions, OptimizationOptions optimizationOptions = OptimizationOptions.All)
        {
            if (EmitType != NonGenericEmitType.DynamicMethod)
            {
                throw new InvalidOperationException("Emit was not created to build a DynamicMethod, thus CreateDelegate cannot be called");
            }

            ValidateDelegateType(delegateType);

            if (InnerEmit.DynMethod == null)
            {
                var dynMethod = new DynamicMethod(Name, ReturnType, ParameterTypes, Module, skipVisibility: true);

                InnerEmit.DynMethod = dynMethod;
            }

            if (CreatedDelegate != null)
            {
                instructions = null;
                return(CreatedDelegate);
            }

            CreatedDelegate = InnerEmit.InnerCreateDelegate(delegateType, out instructions, optimizationOptions);

            return(CreatedDelegate);
        }
コード例 #4
0
        /// <summary>
        /// Produces a code minifiction of CSS assets by using Sergey Kryzhanovsky's CSSO (CSS Optimizer)
        /// </summary>
        /// <param name="assets">Set of CSS assets</param>
        /// <returns>Set of CSS assets with minified text content</returns>
        public IList <IAsset> Minify(IList <IAsset> assets)
        {
            if (assets == null)
            {
                throw new ArgumentException(CoreStrings.Common_ValueIsEmpty, "assets");
            }

            if (assets.Count == 0)
            {
                return(assets);
            }

            var assetsToProcessing = assets.Where(a => a.IsStylesheet && !a.Minified).ToList();

            if (assetsToProcessing.Count == 0)
            {
                return(assets);
            }

            OptimizationOptions options = CreateOptimizationOptions();

            using (var cssOptimizer = new CssOptimizer(_createJsEngineInstance, options))
            {
                foreach (var asset in assetsToProcessing)
                {
                    InnerMinify(asset, cssOptimizer);
                }
            }

            return(assets);
        }
コード例 #5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="OptimizeDocumentOnlineRequest"/> class.
 /// </summary>
 /// <param name="document">The document.</param>
 /// <param name="options">The document optimization options.</param>
 /// <param name="loadEncoding">Encoding that will be used to load an HTML (or TXT) document if the encoding is not specified in HTML.</param>
 /// <param name="password">Password for opening an encrypted document.</param>
 /// <param name="destFileName">Result path of the document after the operation. If this parameter is omitted then result of the operation will be saved as the source document.</param>
 /// <param name="revisionAuthor">Initials of the author to use for revisions.If you set this parameter and then make some changes to the document programmatically, save the document and later open the document in MS Word you will see these changes as revisions.</param>
 /// <param name="revisionDateTime">The date and time to use for revisions.</param>
 public OptimizeDocumentOnlineRequest(System.IO.Stream document, OptimizationOptions options, string loadEncoding = null, string password = null, string destFileName = null, string revisionAuthor = null, string revisionDateTime = null)
 {
     this.Document         = document;
     this.Options          = options;
     this.LoadEncoding     = loadEncoding;
     this.Password         = password;
     this.DestFileName     = destFileName;
     this.RevisionAuthor   = revisionAuthor;
     this.RevisionDateTime = revisionDateTime;
 }
コード例 #6
0
        /// <summary>
        /// Creates a optimization options
        /// </summary>
        /// <returns>Optimization options</returns>
        private OptimizationOptions CreateOptimizationOptions()
        {
            var options = new OptimizationOptions
            {
                Restructure     = !DisableRestructuring,
                ForceMediaMerge = ForceMediaMerge,
                Comments        = Comments
            };

            return(options);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="OptimizeDocumentRequest"/> class.
 /// </summary>
 /// <param name="name">The filename of the input document.</param>
 /// <param name="options">The document optimization options.</param>
 /// <param name="folder">Original document folder.</param>
 /// <param name="storage">Original document storage.</param>
 /// <param name="loadEncoding">Encoding that will be used to load an HTML (or TXT) document if the encoding is not specified in HTML.</param>
 /// <param name="password">Password for opening an encrypted document.</param>
 /// <param name="destFileName">Result path of the document after the operation. If this parameter is omitted then result of the operation will be saved as the source document.</param>
 /// <param name="revisionAuthor">Initials of the author to use for revisions.If you set this parameter and then make some changes to the document programmatically, save the document and later open the document in MS Word you will see these changes as revisions.</param>
 /// <param name="revisionDateTime">The date and time to use for revisions.</param>
 public OptimizeDocumentRequest(string name, OptimizationOptions options, string folder = null, string storage = null, string loadEncoding = null, string password = null, string destFileName = null, string revisionAuthor = null, string revisionDateTime = null)
 {
     this.Name             = name;
     this.Options          = options;
     this.Folder           = folder;
     this.Storage          = storage;
     this.LoadEncoding     = loadEncoding;
     this.Password         = password;
     this.DestFileName     = destFileName;
     this.RevisionAuthor   = revisionAuthor;
     this.RevisionDateTime = revisionDateTime;
 }
コード例 #8
0
ファイル: Emit.cs プロジェクト: csainty/Sigil
        /// <summary>
        /// Converts the CIL stream into a delegate.
        ///
        /// Validation that cannot be run until a method is finished is run, and various instructions
        /// are re-written to choose "optimal" forms (Br may become Br_S, for example).
        ///
        /// Once this method is called the Emit may no longer be modified.
        ///
        /// `instructions` will be set to a representation of the instructions making up the returned delegate.
        /// Note that this string is typically *not* enough to regenerate the delegate, it is available for
        /// debugging purposes only.  Consumers may find it useful to log the instruction stream in case
        /// the returned delegate fails validation (indicative of a bug in Sigil) or
        /// behaves unexpectedly (indicative of a logic bug in the consumer code).
        /// </summary>
        public DelegateType CreateDelegate(out string instructions, OptimizationOptions optimizationOptions = OptimizationOptions.All)
        {
            if (DynMethod == null)
            {
                throw new InvalidOperationException("Emit was not created to build a DynamicMethod, thus CreateDelegate cannot be called");
            }

            if (CreatedDelegate != null)
            {
                instructions = null;
                return(CreatedDelegate);
            }

            CreatedDelegate = (DelegateType)(object)InnerCreateDelegate(typeof(DelegateType), out instructions, optimizationOptions);

            return(CreatedDelegate);
        }
コード例 #9
0
ファイル: Emit.cs プロジェクト: arlm/Sigil-vNext
        /// <summary>
        /// Writes the CIL stream out to the ConstructorBuilder used to create this Emit.
        ///
        /// Validation that cannot be run until a method is finished is run, and various instructions
        /// are re-written to choose "optimal" forms (Br may become Br_S, for example).
        ///
        /// Once this method is called the Emit may no longer be modified.
        ///
        /// Returns a ConstructorBuilder, which can be used to define overrides or for further inspection.
        ///
        /// `instructions` will be set to a representation of the instructions making up the returned constructor.
        /// Note that this string is typically *not* enough to regenerate the constructor, it is available for
        /// debugging purposes only.  Consumers may find it useful to log the instruction stream in case
        /// the returned constructor fails validation (indicative of a bug in Sigil) or
        /// behaves unexpectedly (indicative of a logic bug in the consumer code).
        /// </summary>
        public ConstructorBuilder CreateTypeInitializer(out string instructions, OptimizationOptions optimizationOptions = OptimizationOptions.All)
        {
            if (EmitType != NonGenericEmitType.TypeInitializer)
            {
                throw new InvalidOperationException("Emit was not created to build a type initializer, thus CreateTypeInitializer cannot be called");
            }

            if (CreatedConstructor != null)
            {
                instructions = null;
                return(CreatedConstructor);
            }

            var constructorBuilder = TypeBuilder.DefineTypeInitializer();

            InnerEmit.ConstrBuilder = constructorBuilder;

            CreatedConstructor = InnerEmit.CreateTypeInitializer(out instructions, optimizationOptions);

            return(CreatedConstructor);
        }
コード例 #10
0
ファイル: Emit.cs プロジェクト: arlm/Sigil-vNext
        /// <summary>
        /// Writes the CIL stream out to the ConstructorBuilder used to create this Emit.
        ///
        /// Validation that cannot be run until a method is finished is run, and various instructions
        /// are re-written to choose "optimal" forms (Br may become Br_S, for example).
        ///
        /// Once this method is called the Emit may no longer be modified.
        ///
        /// Returns a ConstructorBuilder, which can be used to define overrides or for further inspection.
        ///
        /// `instructions` will be set to a representation of the instructions making up the returned constructor.
        /// Note that this string is typically *not* enough to regenerate the constructor, it is available for
        /// debugging purposes only.  Consumers may find it useful to log the instruction stream in case
        /// the returned constructor fails validation (indicative of a bug in Sigil) or
        /// behaves unexpectedly (indicative of a logic bug in the consumer code).
        /// </summary>
        public ConstructorBuilder CreateConstructor(out string instructions, OptimizationOptions optimizationOptions = OptimizationOptions.All)
        {
            if (EmitType != NonGenericEmitType.Constructor)
            {
                throw new InvalidOperationException("Emit was not created to build a constructor, thus CreateConstructor cannot be called");
            }

            if (CreatedConstructor != null)
            {
                instructions = null;
                return(CreatedConstructor);
            }

            var constructorBuilder = TypeBuilder.DefineConstructor(Attributes, CallingConvention, ParameterTypes);

            InnerEmit.ConstrBuilder = constructorBuilder;

            CreatedConstructor = InnerEmit.CreateConstructor(out instructions, optimizationOptions);

            return(CreatedConstructor);
        }
コード例 #11
0
ファイル: Emit.cs プロジェクト: arlm/Sigil-vNext
        /// <summary>
        /// Writes the CIL stream out to the MethodBuilder used to create this Emit.
        ///
        /// Validation that cannot be run until a method is finished is run, and various instructions
        /// are re-written to choose "optimal" forms (Br may become Br_S, for example).
        ///
        /// Once this method is called the Emit may no longer be modified.
        ///
        /// Returns a MethodBuilder, which can be used to define overrides or for further inspection.
        ///
        /// `instructions` will be set to a representation of the instructions making up the returned method.
        /// Note that this string is typically *not* enough to regenerate the method, it is available for
        /// debugging purposes only.  Consumers may find it useful to log the instruction stream in case
        /// the returned method fails validation (indicative of a bug in Sigil) or
        /// behaves unexpectedly (indicative of a logic bug in the consumer code).
        /// </summary>
        public MethodBuilder CreateMethod(out string instructions, OptimizationOptions optimizationOptions = OptimizationOptions.All)
        {
            if (EmitType != NonGenericEmitType.Method)
            {
                throw new InvalidOperationException("Emit was not created to build a method, thus CreateMethod cannot be called");
            }

            if (CreatedMethod != null)
            {
                instructions = null;
                return(CreatedMethod);
            }

            var methodBuilder = TypeBuilder.DefineMethod(Name, Attributes, CallingConvention, ReturnType, ParameterTypes);

            InnerEmit.MtdBuilder = methodBuilder;

            CreatedMethod = InnerEmit.CreateMethod(out instructions, optimizationOptions);

            return(CreatedMethod);
        }
コード例 #12
0
        /// <summary>
        /// Produces a code minifiction of CSS asset by using Sergey Kryzhanovsky's CSSO (CSS Optimizer)
        /// </summary>
        /// <param name="asset">CSS asset</param>
        /// <returns>CSS asset with minified text content</returns>
        public IAsset Minify(IAsset asset)
        {
            if (asset == null)
            {
                throw new ArgumentException(CoreStrings.Common_ValueIsEmpty, "asset");
            }

            if (asset.Minified)
            {
                return(asset);
            }

            OptimizationOptions options = CreateOptimizationOptions();

            using (var cssOptimizer = new CssOptimizer(_createJsEngineInstance, options))
            {
                InnerMinify(asset, cssOptimizer);
            }

            return(asset);
        }
コード例 #13
0
        static void Main()
        {
            // Create Bytescout.PDFExtractor.DocumentOptimizer instance
            using (DocumentOptimizer optimizer = new DocumentOptimizer("demo", "demo"))
            {
                // Try various optimization options
                OptimizationOptions optimizationOptions = new OptimizationOptions();
                optimizationOptions.ImageOptimizationFormat = ImageOptimizationFormat.JPEG;
                optimizationOptions.JPEGQuality             = 25;
                optimizationOptions.ResampleImages          = true;
                optimizationOptions.ResamplingResolution    = 120;

                // Optimize document and save it to new file
                optimizer.OptimizeDocument(@".\sample1.pdf", @".\optimized.pdf", optimizationOptions);
            }

            Console.WriteLine("Optimized document has been saved as " + Path.GetFullPath(@".\optimized.pdf"));
            Console.WriteLine();
            Console.WriteLine("Press any key...");
            Console.ReadLine();
        }
コード例 #14
0
        public static void Run()
        {
            // ExStart:OptimizeFileSize
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();

            // Open document
            Document pdfDocument = new Document(dataDir + "OptimizeDocument.pdf");

            OptimizationOptions optimizationOptions = new OptimizationOptions();

            optimizationOptions.LinkDuplcateStreams = true;
            optimizationOptions.RemoveUnusedObjects = true;
            optimizationOptions.RemoveUnusedStreams = true;
            optimizationOptions.ImageCompressionOptions.CompressImages = true;
            optimizationOptions.ImageCompressionOptions.ImageQuality   = 10;
            // Optimzie the file size by removing unused objects
            pdfDocument.OptimizeResources(optimizationOptions);
            dataDir = dataDir + "OptimizeFileSize_out.pdf";
            // Save output document
            pdfDocument.Save(dataDir);
            // ExEnd:OptimizeFileSize
            Console.WriteLine("\nFile size optimized successfully.\nFile saved at " + dataDir);
        }
コード例 #15
0
ファイル: Emit.cs プロジェクト: csainty/Sigil
        private void Seal(OptimizationOptions optimizationOptions)
        {
            if ((optimizationOptions & ~OptimizationOptions.All) != 0)
            {
                throw new ArgumentException("optimizationOptions contained unknown flags, found " + optimizationOptions);
            }

            if ((optimizationOptions & OptimizationOptions.EnableTrivialCastEliding) != 0)
            {
                ElideCasts();
            }

            InjectTailCall();
            InjectReadOnly();

            if ((optimizationOptions & OptimizationOptions.EnableBranchPatching) != 0)
            {
                PatchBranches();
            }

            Validate();

            Invalidated = true;
        }
コード例 #16
0
        /// <summary>
        /// Produces a code minifiction of CSS asset by using Sergey Kryzhanovsky's CSSO (CSS Optimizer)
        /// </summary>
        /// <param name="asset">CSS asset</param>
        /// <returns>CSS asset with minified text content</returns>
        public IAsset Minify(IAsset asset)
        {
            if (asset == null)
            {
                throw new ArgumentNullException(
                          nameof(asset),
                          string.Format(CoreStrings.Common_ArgumentIsNull, nameof(asset))
                          );
            }

            if (asset.Minified)
            {
                return(asset);
            }

            OptimizationOptions options = CreateOptimizationOptions();

            using (var cssOptimizer = new CssOptimizer(_createJsEngineInstance, options))
            {
                InnerMinify(asset, cssOptimizer);
            }

            return(asset);
        }
コード例 #17
0
        public OptimizationResult Optimize(ShaderType shaderType, string source, OptimizationOptions options)
        {
            var sourcePtr = Marshal.StringToHGlobalAnsi(source);
            var shader = NativeMethods.glslopt_optimize(_ctx, shaderType, sourcePtr, (uint) options);
            if (shader == IntPtr.Zero)
                throw new Exception("Failed to create shader");

            try
            {
                if (!NativeMethods.glslopt_get_status(shader))
                {
                    var log = NativeMethods.glslopt_get_log(shader);
                    var info = Marshal.PtrToStringAnsi(log);
                    throw new Exception("Error parsing shader: " + info);
                }

                var outputPtr = NativeMethods.glslopt_get_output(shader);
                var output = Marshal.PtrToStringAnsi(outputPtr);

                var result = new OptimizationResult();
                result.OutputCode = output;

                var inputCount = NativeMethods.glslopt_shader_get_input_count(shader);
                for (int i = 0; i < inputCount; i++)
                {
                    IntPtr outName;
                    int outLocation, outArraySize, outMatSize, outVecSize;
                    BasicType outType;
                    Precision outPrec;

                    NativeMethods.glslopt_shader_get_input_desc(shader, i,
                        out outName,
                        out outType,
                        out outPrec,
                        out outVecSize,
                        out outMatSize,
                        out outArraySize,
                        out outLocation);
                    var name = Marshal.PtrToStringAnsi(outName);

                    result.Inputs.Add(new VariableInfo
                    {
                        Name = name,
                        Type = outType,
                        Precision = outPrec,
                        VectorSize = outVecSize,
                        MatrixSize = outMatSize,
                        ArraySize = outArraySize,
                        Location = outLocation
                    });
                }

                var uniformCount = NativeMethods.glslopt_shader_get_uniform_count(shader);
                for (int i = 0; i < uniformCount; i++)
                {
                    IntPtr outName;
                    int outLocation, outArraySize, outMatSize, outVecSize;
                    BasicType outType;
                    Precision outPrec;

                    NativeMethods.glslopt_shader_get_uniform_desc(shader, i,
                        out outName,
                        out outType,
                        out outPrec,
                        out outVecSize,
                        out outMatSize,
                        out outArraySize,
                        out outLocation);
                    var name = Marshal.PtrToStringAnsi(outName);

                    result.Uniforms.Add(new VariableInfo
                    {
                        Name = name,
                        Type = outType,
                        Precision = outPrec,
                        VectorSize = outVecSize,
                        MatrixSize = outMatSize,
                        ArraySize = outArraySize,
                        Location = outLocation
                    });
                }

                var textureCount = NativeMethods.glslopt_shader_get_texture_count(shader);
                for (int i = 0; i < textureCount; i++)
                {
                    IntPtr outName;
                    int outLocation, outArraySize, outMatSize, outVecSize;
                    BasicType outType;
                    Precision outPrec;

                    NativeMethods.glslopt_shader_get_texture_desc(shader, i,
                        out outName,
                        out outType,
                        out outPrec,
                        out outVecSize,
                        out outMatSize,
                        out outArraySize,
                        out outLocation);
                    var name = Marshal.PtrToStringAnsi(outName);

                    result.Textures.Add(new VariableInfo
                    {
                        Name = name,
                        Type = outType,
                        Precision = outPrec,
                        VectorSize = outVecSize,
                        MatrixSize = outMatSize,
                        ArraySize = outArraySize,
                        Location = outLocation
                    });
                }

                int outMath, outTex, outFlow;
                NativeMethods.glslopt_shader_get_stats(shader, out outMath, out outTex, out outFlow);
                result.Statistics.ApproxMathInstructions = outMath;
                result.Statistics.ApproxTextureInstructions = outTex;
                result.Statistics.ApproxControlFlowInstructions = outFlow;

                return result;
            }
            finally
            {
                NativeMethods.glslopt_shader_delete(shader);
            }
        }
コード例 #18
0
ファイル: EmitShorthand.cs プロジェクト: csainty/Sigil
 /// <summary cref="M:Sigil.Emit`1.CreateDelegate(Sigil.OptimizationOptions)" />
 public DelegateType CreateDelegate(OptimizationOptions optimizationOptions = OptimizationOptions.All)
 {
     return(InnerEmit.CreateDelegate(optimizationOptions));
 }
コード例 #19
0
ファイル: Emit.cs プロジェクト: csainty/Sigil
        /// <summary>
        /// Writes the CIL stream out to the ConstructorBuilder used to create this Emit.
        ///
        /// Validation that cannot be run until a method is finished is run, and various instructions
        /// are re-written to choose "optimal" forms (Br may become Br_S, for example).
        ///
        /// Once this method is called the Emit may no longer be modified.
        ///
        /// Returns a ConstructorBuilder, which can be used to define overrides or for further inspection.
        /// </summary>
        public ConstructorBuilder CreateConstructor(OptimizationOptions optimizationOptions = OptimizationOptions.All)
        {
            string ignored;

            return(CreateConstructor(out ignored, optimizationOptions));
        }
コード例 #20
0
ファイル: Emit.cs プロジェクト: arlm/Sigil-vNext
 /// <summary>
 /// Converts the CIL stream into a delegate.
 ///
 /// Validation that cannot be run until a method is finished is run, and various instructions
 /// are re-written to choose "optimal" forms (Br may become Br_S, for example).
 ///
 /// Once this method is called the Emit may no longer be modified.
 ///
 /// `instructions` will be set to a representation of the instructions making up the returned delegate.
 /// Note that this string is typically *not* enough to regenerate the delegate, it is available for
 /// debugging purposes only.  Consumers may find it useful to log the instruction stream in case
 /// the returned delegate fails validation (indicative of a bug in Sigil) or
 /// behaves unexpectedly (indicative of a logic bug in the consumer code).
 /// </summary>
 public DelegateType CreateDelegate <DelegateType>(out string instructions, OptimizationOptions optimizationOptions = OptimizationOptions.All)
 {
     return((DelegateType)(object)CreateDelegate(typeof(DelegateType), out instructions, optimizationOptions));
 }
コード例 #21
0
ファイル: Emit.cs プロジェクト: csainty/Sigil
        /// <summary>
        /// Writes the CIL stream out to the MethodBuilder used to create this Emit.
        ///
        /// Validation that cannot be run until a method is finished is run, and various instructions
        /// are re-written to choose "optimal" forms (Br may become Br_S, for example).
        ///
        /// Once this method is called the Emit may no longer be modified.
        ///
        /// Returns a MethodBuilder, which can be used to define overrides or for further inspection.
        /// </summary>
        public MethodBuilder CreateMethod(OptimizationOptions optimizationOptions = OptimizationOptions.All)
        {
            string ignored;

            return(CreateMethod(out ignored, optimizationOptions));
        }
コード例 #22
0
 /// <summary>
 /// Converts the CIL stream into a delegate.
 ///
 /// Validation that cannot be run until a method is finished is run, and various instructions
 /// are re-written to choose "optimal" forms (Br may become Br_S, for example).
 ///
 /// Once this method is called the Emit may no longer be modified.
 /// </summary>
 public DelegateType CreateDelegate(OptimizationOptions optimizationOptions = OptimizationOptions.All)
 {
     return(CreateDelegate(instructions: out _, optimizationOptions));
 }
コード例 #23
0
ファイル: Emit.cs プロジェクト: csainty/Sigil
        /// <summary>
        /// Converts the CIL stream into a delegate.
        ///
        /// Validation that cannot be run until a method is finished is run, and various instructions
        /// are re-written to choose "optimal" forms (Br may become Br_S, for example).
        ///
        /// Once this method is called the Emit may no longer be modified.
        /// </summary>
        public DelegateType CreateDelegate(OptimizationOptions optimizationOptions = OptimizationOptions.All)
        {
            string ignored;

            return(CreateDelegate(out ignored, optimizationOptions));
        }
コード例 #24
0
 /// <summary>
 /// Writes the CIL stream out to the MethodBuilder used to create this Emit.
 ///
 /// Validation that cannot be run until a method is finished is run, and various instructions
 /// are re-written to choose "optimal" forms (Br may become Br_S, for example).
 ///
 /// Once this method is called the Emit may no longer be modified.
 ///
 /// Returns a MethodBuilder, which can be used to define overrides or for further inspection.
 /// </summary>
 public MethodBuilder CreateMethod(OptimizationOptions optimizationOptions = OptimizationOptions.All)
 {
     return(CreateMethod(instructions: out _, optimizationOptions));
 }
コード例 #25
0
ファイル: Emit.cs プロジェクト: csainty/Sigil
        internal Delegate InnerCreateDelegate(Type delegateType, out string instructions, OptimizationOptions optimizationOptions)
        {
            Seal(optimizationOptions);

            var il = DynMethod.GetILGenerator();

            instructions = IL.UnBuffer(il);

            AutoNamer.Release(this);

            return(DynMethod.CreateDelegate(delegateType));
        }
コード例 #26
0
 /// <summary>
 /// Writes the CIL stream out to the ConstructorBuilder used to create this Emit.
 ///
 /// Validation that cannot be run until a method is finished is run, and various instructions
 /// are re-written to choose "optimal" forms (Br may become Br_S, for example).
 ///
 /// Once this method is called the Emit may no longer be modified.
 ///
 /// Returns a ConstructorBuilder, which can be used to define overrides or for further inspection.
 /// </summary>
 public ConstructorBuilder CreateTypeInitializer(OptimizationOptions optimizationOptions = OptimizationOptions.All)
 {
     return(CreateTypeInitializer(instructions: out _, optimizationOptions));
 }
コード例 #27
0
 /// <summary cref="M:Sigil.Emit.NonGeneric.Emit`1.CreateDelegate(System.Type, Sigil.OptimizationOptions)" />
 public object CreateDelegate(Type delegateType, OptimizationOptions optimizationOptions = OptimizationOptions.All)
 {
     return(InnerEmit.CreateDelegate(delegateType, optimizationOptions));
 }
コード例 #28
0
        public OptimizationResult Optimize(ShaderType shaderType, string source, OptimizationOptions options)
        {
            var sourcePtr = Marshal.StringToHGlobalAnsi(source);
            var shader    = NativeMethods.glslopt_optimize(_ctx, shaderType, sourcePtr, (uint)options);

            if (shader == IntPtr.Zero)
            {
                throw new Exception("Failed to create shader");
            }

            try
            {
                if (!NativeMethods.glslopt_get_status(shader))
                {
                    var log  = NativeMethods.glslopt_get_log(shader);
                    var info = Marshal.PtrToStringAnsi(log);
                    throw new Exception("Error parsing shader: " + info);
                }

                var outputPtr = NativeMethods.glslopt_get_output(shader);
                var output    = Marshal.PtrToStringAnsi(outputPtr);

                var result = new OptimizationResult();
                result.OutputCode = output;

                var inputCount = NativeMethods.glslopt_shader_get_input_count(shader);
                for (int i = 0; i < inputCount; i++)
                {
                    IntPtr    outName;
                    int       outLocation, outArraySize, outMatSize, outVecSize;
                    BasicType outType;
                    Precision outPrec;

                    NativeMethods.glslopt_shader_get_input_desc(shader, i,
                                                                out outName,
                                                                out outType,
                                                                out outPrec,
                                                                out outVecSize,
                                                                out outMatSize,
                                                                out outArraySize,
                                                                out outLocation);
                    var name = Marshal.PtrToStringAnsi(outName);

                    result.Inputs.Add(new VariableInfo
                    {
                        Name       = name,
                        Type       = outType,
                        Precision  = outPrec,
                        VectorSize = outVecSize,
                        MatrixSize = outMatSize,
                        ArraySize  = outArraySize,
                        Location   = outLocation
                    });
                }

                var uniformCount = NativeMethods.glslopt_shader_get_uniform_count(shader);
                for (int i = 0; i < uniformCount; i++)
                {
                    IntPtr    outName;
                    int       outLocation, outArraySize, outMatSize, outVecSize;
                    BasicType outType;
                    Precision outPrec;

                    NativeMethods.glslopt_shader_get_uniform_desc(shader, i,
                                                                  out outName,
                                                                  out outType,
                                                                  out outPrec,
                                                                  out outVecSize,
                                                                  out outMatSize,
                                                                  out outArraySize,
                                                                  out outLocation);
                    var name = Marshal.PtrToStringAnsi(outName);

                    result.Uniforms.Add(new VariableInfo
                    {
                        Name       = name,
                        Type       = outType,
                        Precision  = outPrec,
                        VectorSize = outVecSize,
                        MatrixSize = outMatSize,
                        ArraySize  = outArraySize,
                        Location   = outLocation
                    });
                }

                var textureCount = NativeMethods.glslopt_shader_get_texture_count(shader);
                for (int i = 0; i < textureCount; i++)
                {
                    IntPtr    outName;
                    int       outLocation, outArraySize, outMatSize, outVecSize;
                    BasicType outType;
                    Precision outPrec;

                    NativeMethods.glslopt_shader_get_texture_desc(shader, i,
                                                                  out outName,
                                                                  out outType,
                                                                  out outPrec,
                                                                  out outVecSize,
                                                                  out outMatSize,
                                                                  out outArraySize,
                                                                  out outLocation);
                    var name = Marshal.PtrToStringAnsi(outName);

                    result.Textures.Add(new VariableInfo
                    {
                        Name       = name,
                        Type       = outType,
                        Precision  = outPrec,
                        VectorSize = outVecSize,
                        MatrixSize = outMatSize,
                        ArraySize  = outArraySize,
                        Location   = outLocation
                    });
                }

                int outMath, outTex, outFlow;
                NativeMethods.glslopt_shader_get_stats(shader, out outMath, out outTex, out outFlow);
                result.Statistics.ApproxMathInstructions        = outMath;
                result.Statistics.ApproxTextureInstructions     = outTex;
                result.Statistics.ApproxControlFlowInstructions = outFlow;

                return(result);
            }
            finally
            {
                NativeMethods.glslopt_shader_delete(shader);
            }
        }
コード例 #29
0
        public RawOptimizedState Optimize(
			Network net,
			OptimizationOptions options)
        {
            var context = SolverContext.GetContext();
            context.ClearModel();
            var model = context.CreateModel();

            // Load in nodes, links, orders as lists.
            var nodes = net.Nodes.ToList();
            var links = net.Links.ToList();
            var orders = net.Orders.ToList();

            // Make sure the existing optimization has default weights set.
            if(options.AllowLocomotiveCapacityExpansion)
            {
                if(net.OptimizationResult.DefaultLinkExpansion == null)
                {
                    net.OptimizationResult.DefaultLinkExpansion = new ExpansionParameters()
                    {
                        CapacityExpansionMaxPossible = 100,
                        CapacityExpansionCostPerUnit = 10000
                    };
                }
            }
            if(options.AllowNodeCapacityExpansion)
            {
                if(net.OptimizationResult.DefaultNodeExpansion == null)
                {
                    net.OptimizationResult.DefaultNodeExpansion = new ExpansionParameters()
                    {
                        CapacityExpansionMaxPossible = 10000,
                        CapacityExpansionCostPerUnit = 1000
                    };
                }
            }

            #region Decision variables, car costs
            var flowDecisions = new Dictionary<Node,Dictionary<Link,Decision>>();
            Term totalCarCosts = 0;

            var expandNodeDecisions = new Dictionary<NodeOptimized,Decision>();
            var expandLinkDecisions = new Dictionary<LinkOptimized,Decision>();
            Term totalExpandCosts = 0;

            // One per link for each node.
            foreach(var node in nodes)
            {
                flowDecisions[node] = new Dictionary<Link,Decision>();
                foreach(var link in links)
                {
                    flowDecisions[node][link] = new Decision(
                        Domain.IntegerNonnegative,
                        "Node_" + node.ID + "_cars_" +
                        link.From.ID + "_to_" + link.To.ID
                    );

                    model.AddDecision(flowDecisions[node][link]);

                    // Car cost for this link.
                    totalCarCosts += flowDecisions[node][link] * link.Distance * net.CarCostPerMile;
                }
            }
            // Create the decision vars for expansion, if necessary.
            if(options.AllowNodeCapacityExpansion)
            {
                foreach(var node in net.OptimizationResult.Nodes)
                {
                    expandNodeDecisions[node] = new Decision(
                        Domain.IntegerNonnegative,
                        "Node_" + node.Node.ID + "_expansion"
                    );

                    model.AddDecision(expandNodeDecisions[node]);

                    if(node.Expansion == null)
                        node.Expansion = new ExpansionParameters();

                    var perUnitCost = node.Expansion.CapacityExpansionCostPerUnit ??
                        (int)net.OptimizationResult.DefaultNodeExpansion.CapacityExpansionCostPerUnit;
                    int maxPossible = node.Expansion.CapacityExpansionMaxPossible ??
                        (int)net.OptimizationResult.DefaultNodeExpansion.CapacityExpansionMaxPossible;

                    totalExpandCosts += expandNodeDecisions[node] * perUnitCost;

                    model.AddConstraint("Node_exp_cap_" + node.Node.ID,
                        expandNodeDecisions[node] <= maxPossible);
                }
            }
            if(options.AllowLocomotiveCapacityExpansion)
            {
                foreach(var link in net.OptimizationResult.Links)
                {
                    expandLinkDecisions[link] = new Decision(
                        Domain.IntegerNonnegative,
                        "Link_" + link.Link.ID + "_expansion"
                    );

                    model.AddDecision(expandLinkDecisions[link]);

                    if(link.Expansion == null)
                        link.Expansion = new ExpansionParameters();

                    var perUnitCost = link.Expansion.CapacityExpansionCostPerUnit ??
                        (int)net.OptimizationResult.DefaultLinkExpansion.CapacityExpansionCostPerUnit;
                    int maxPossible = link.Expansion.CapacityExpansionMaxPossible ??
                        (int)net.OptimizationResult.DefaultLinkExpansion.CapacityExpansionMaxPossible;

                    totalExpandCosts += expandLinkDecisions[link] * perUnitCost;

                    model.AddConstraint("Link_exp_cap_" + link.Link.ID,
                        expandLinkDecisions[link] <= maxPossible);
                }
            }
            #endregion

            #region Locomotive decision variables, locomotive costs
            Term totalLocomotiveCosts = 0;
            var locomotiveDecisions = new Dictionary<Link, Decision>();
            foreach(var link in links)
            {
                locomotiveDecisions[link] = new Decision(Domain.IntegerNonnegative,
                    "Locomotives_" + link.From.ID + "_to_" + link.To.ID);
                model.AddDecision(locomotiveDecisions[link]);

                // Constraint on max locomotives.
                // If optimized, number of locomotives is allowed to be below the capacity.
                Term locos = locomotiveDecisions[link];
                if(options.AllowLocomotiveCapacityExpansion)
                {
                    Decision expand = expandLinkDecisions.FirstOrDefault(
                        l => l.Key.Link == link
                    ).Value;

                    model.AddConstraint("Maxloco_" + link.From.ID + "_to_" + link.To.ID,
                        locos <= link.MaxTrains + expand);
                }
                else
                {
                    model.AddConstraint("Maxloco_" + link.From.ID + "_to_" + link.To.ID,
                        locos <= link.MaxTrains);
                }

                Term locoCost = link.Distance * locomotiveDecisions[link]
                    * (net.NonFuelCostPerMile + net.FuelCostPerMile * link.FuelAdjustment);
                totalLocomotiveCosts += locoCost;
            }
            #endregion

            #region Constraint 1: Order Flow
            // For loop so that indices are kept.
            foreach(var fulfiller in nodes)
            {
                foreach(var fulfilled in nodes)
                {
                    var fulfilledOrders = orders.Where(o => o.Origin == fulfiller);
                    if(fulfilled != fulfiller)
                        fulfilledOrders = fulfilledOrders.Where(o => o.Destination == fulfilled);

                    // Required flow on nodeFulfilled to satisfy the order.
                    int requiredFlow = 0;
                    foreach(Order order in fulfilledOrders)
                    {
                        if(fulfilled == fulfiller)
                            requiredFlow += order.Cars;
                        else
                            requiredFlow -= order.Cars;
                    }

                    // Sum of decision variables that should match the required flow.
                    Term actualFlow = 0;
                    // Get links that go to and from fulfilled.
                    var fromLinks = links.Where(l => l.From == fulfilled);
                    var toLinks = links.Where(l => l.To == fulfilled);
                    // Go through related decision variables.
                    foreach(var link in fromLinks)
                    {
                        // Decision variable index.
                        actualFlow += flowDecisions[fulfiller][link];
                    }
                    foreach(var link in toLinks)
                    {
                        // Decision variable index.
                        actualFlow -= flowDecisions[fulfiller][link];
                    }

                    model.AddConstraint("_" + fulfiller.ID + "_fulfilling_" + fulfilled.ID,
                        actualFlow == requiredFlow);
                }
            }
            #endregion

            #region Constraint 2: Link Capacity
            foreach(var link in links)
            {
                // Total amount of flow over this link, summed for all car sources.
                Term totalFlow = 0;

                foreach(var node in nodes)
                {
                    totalFlow += flowDecisions[node][link];
                }

                Term linkCapacity = locomotiveDecisions[link] * net.MaxCarsPerTrain;
                if(options.AllowLocomotiveCapacityExpansion)
                {
                    LinkOptimized optNode = net.OptimizationResult.Links.Where(n => n.Link == link).First();
                    // If the user has set max possible expansions for flow in or out, use them.

                    model.AddConstraint("Link_" + link.ID + "_cap",
                        totalFlow <= linkCapacity + expandLinkDecisions[optNode]);
                }
                else
                {
                    model.AddConstraint("Link_" + link.ID + "_cap",
                        totalFlow <= linkCapacity);
                }
            }
            #endregion

            #region Constraint 3/4: Node Capacity
            foreach(var node in nodes)
            {
                // Get all in and out links.
                var outLinks = links.Where(l => l.From == node);
                var inLinks = links.Where(l => l.To == node);

                Term flowOut = 0;
                Term flowIn = 0;

                foreach(var nodeo in nodes)
                {
                    foreach(var link in outLinks)
                        flowOut += flowDecisions[nodeo][link];
                    foreach(var link in inLinks)
                        flowIn += flowDecisions[nodeo][link];
                }

                if(options.AllowNodeCapacityExpansion)
                {
                    NodeOptimized optNode = net.OptimizationResult.Nodes.Where(n => n.Node == node).First();
                    // If the user has set max possible expansions for flow in or out, use them.

                    model.AddConstraint("Node_" + node.ID + "_capacity_out",
                        flowOut <= node.CarCapacity + expandNodeDecisions[optNode]);
                    model.AddConstraint("Node_" + node.ID + "_capacity_in",
                        flowIn <= node.CarCapacity + expandNodeDecisions[optNode]);
                    // If there is no max, make no constraint.
                }
                else
                {
                    model.AddConstraint("Node_" + node.ID + "_capacity_out",
                        flowOut <= node.CarCapacity);
                    model.AddConstraint("Node_" + node.ID + "_capacity_in",
                        flowIn <= node.CarCapacity);
                }
            }
            #endregion

            #region Objective Function
            // Objective function. (Minimize)
            Term totalCost = totalCarCosts + totalLocomotiveCosts + totalExpandCosts;
            model.AddGoal("TotalCost", GoalKind.Minimize, totalCost);
            #endregion

            //Directive directive = new LpSolveDirective();
            //Directive directive = new SimplexDirective();
            Directive directive = new GurobiDirective();
            //Directive directive = new MixedIntegerProgrammingDirective();

            directive.TimeLimit = TIMEOUT_MAX_SECONDS * 1000;

            var solution = context.Solve(directive);

            var extractedFlowDec = new Dictionary<Node, Dictionary<Link, int>>();
            var extractedLocoDec = new Dictionary<Link, int>();

            foreach(var nvp in flowDecisions)
            {
                extractedFlowDec[nvp.Key] = new Dictionary<Link,int>();
                foreach(var lvp in nvp.Value)
                {
                    extractedFlowDec[nvp.Key][lvp.Key] = (int)lvp.Value.ToDouble();
                }
            }
            foreach(var lvp in locomotiveDecisions)
            {
                extractedLocoDec[lvp.Key] = (int)lvp.Value.ToDouble();
            }

            foreach(var nvp in expandNodeDecisions)
            {
                nvp.Key.ExpansionSuggested = (int)nvp.Value.ToDouble();
            }
            foreach(var lvp in expandLinkDecisions)
            {
                lvp.Key.ExpansionSuggested = (int)lvp.Value.ToDouble();
            }

            // Extract the suggestion cost. (Don't know a better way to do this.)
            double suggestionCapitalCost = 0.0;

            if(options.AllowNodeCapacityExpansion)
            {
                foreach(var node in net.OptimizationResult.Nodes)
                {
                    var perUnitCost = node.Expansion.CapacityExpansionCostPerUnit ??
                        (int)net.OptimizationResult.DefaultNodeExpansion.CapacityExpansionCostPerUnit;

                    suggestionCapitalCost += expandNodeDecisions[node].ToDouble() * perUnitCost;
                }
            }
            if(options.AllowLocomotiveCapacityExpansion)
            {
                foreach(var link in net.OptimizationResult.Links)
                {
                    var perUnitCost = link.Expansion.CapacityExpansionCostPerUnit ??
                        (int)net.OptimizationResult.DefaultLinkExpansion.CapacityExpansionCostPerUnit;

                    suggestionCapitalCost += expandLinkDecisions[link].ToDouble() * perUnitCost;
                }
            }

            RawOptimizedState.RawQuality q;
            switch(solution.Quality)
            {
                case SolverQuality.Optimal:
                    q = RawOptimizedState.RawQuality.Solved;
                    break;

                case SolverQuality.Infeasible:
                    q = RawOptimizedState.RawQuality.Infeasible;
                    break;

                case SolverQuality.InfeasibleOrUnbounded:
                case SolverQuality.Unbounded:
                    q = RawOptimizedState.RawQuality.Unbounded;
                    break;

                case SolverQuality.Unknown:
                case SolverQuality.Feasible:
                default:
                    q = RawOptimizedState.RawQuality.TimedOut;
                    break;
            }
            var rawState = new RawOptimizedState()
            {
                solvedNetwork = net,
                flowDecisions = extractedFlowDec,
                locomotiveDecisions = extractedLocoDec,
                totalCost = (int)(model.Goals.First().ToDouble() - suggestionCapitalCost),
                suggestionCapitalCost = (int)suggestionCapitalCost,
                Quality = q
            };

            return rawState;
        }