Exemplo n.º 1
0
            public static void Run()
            {
                SimpleCounterTestbench tb = new SimpleCounterTestbench();

                DesignContext.Instance.Elaborate();

                ///remember start time
                Start = System.DateTime.Now.Ticks;

                DesignContext.Instance.Simulate(Cycles * SimpleCounterTestbench.ClockPeriod);

#if RUNANALYSIS
                // Now convert the design to VHDL and embed it into a Xilinx ISE project
                XilinxProject project = new XilinxProject(@".\hdl_output", "SimpleCounter");
                project.PutProperty(EXilinxProjectProperties.DeviceFamily, EDeviceFamily.Spartan3);
                project.PutProperty(EXilinxProjectProperties.Device, EDevice.xc3s1500l);
                project.PutProperty(EXilinxProjectProperties.Package, EPackage.fg676);
                project.PutProperty(EXilinxProjectProperties.SpeedGrade, ESpeedGrade._4);
                project.PutProperty(EXilinxProjectProperties.PreferredLanguage, EHDL.VHDL);

                VHDLGenerator codeGen = new VHDLGenerator();
                SynthesisEngine.Create(DesignContext.Instance, project).Synthesize(codeGen);
                project.Save();
#endif
            }
Exemplo n.º 2
0
        public static void RunTest()
        {
            DesignContext.Reset();

            TestHLS_CFlow2_Testbench tb = new TestHLS_CFlow2_Testbench();

            DesignContext.Instance.Elaborate();
            DesignContext.Instance.Simulate(new Time(100.0, ETimeUnit.us));
            DesignContext.Stop();
            XilinxIntegration.RegisterIPCores(DesignContext.Instance.Descriptor);
            DesignContext.Instance.CompleteAnalysis();

            XC6VLX75T_FF484 fpga = new XC6VLX75T_FF484()
            {
                SpeedGrade        = ESpeedGrade._2,
                TopLevelComponent = tb.DUT
            };

            fpga.Testbenches.Add(tb);
            fpga.Synthesize(@".\hdl_out_TestHLS_CFlow2", "TestHLS_CFlow2");
            var eng = SynthesisEngine.Create(
                DesignContext.Instance, new DocumentationProject(@".\hdl_out_TestHLS_CFlow2\doc"));

            eng.Synthesize(new DocumentationGenerator());
        }
Exemplo n.º 3
0
        public void TestLearnSubstringPositiveAbsPosSecOcurrence()
        {
            Result <Grammar> grammar = CompileGrammar();
            SynthesisEngine  prose   = ConfigureSynthesis(grammar.Value);

            State firstInput  = State.CreateForExecution(grammar.Value.InputSymbol, "16-Feb-2016");
            State secondInput = State.CreateForExecution(grammar.Value.InputSymbol, "14-Jan-2012");
            var   examples    = new Dictionary <State, object> {
                { firstInput, "16" }, { secondInput, "12" }
            };
            var spec = new ExampleSpec(examples);

            ProgramSet learnedSet = prose.LearnGrammar(spec);

            IEnumerable <ProgramNode> programs = learnedSet.RealizedPrograms;
            ProgramNode firstProgram           = programs.First();
            var         output = firstProgram.Invoke(firstInput) as string;

            Assert.AreEqual("16", output);
            output = firstProgram.Invoke(secondInput) as string;
            Assert.AreEqual("12", output);
            State differentInput = State.CreateForExecution(grammar.Value.InputSymbol, "15-Apr-1500");

            output = programs.First().Invoke(differentInput) as string;
            Assert.AreEqual("00", output);
        }
Exemplo n.º 4
0
        public void TestLearnAdd()
        {
            var grammar = DSLCompiler.LoadGrammarFromFile("../../../ProseDSLModels.grammar");

            printGrammar(grammar);
            SynthesisEngine prose = new SynthesisEngine(grammar.Value);

            double[] inp1 = new double[4] {
                10.9, 15.0, -14.5, 12.3
            };
            double[] out1  = add(inp1);
            var      input = State.Create(grammar.Value.InputSymbol, inp1);

            var examples = new Dictionary <State, object> {
                { input, out1 }
            };
            var spec       = new ExampleSpec(examples);
            var learnedSet = prose.LearnGrammar(spec);
            var output     = (double[])learnedSet.RealizedPrograms.First().Invoke(input);

            stdoutprogram(learnedSet.RealizedPrograms.First().ToString(), "Add");
            Assert.AreEqual(23.7, output[0], 0.001d);
            TestContext.WriteLine("Running random exmaples for LearnAdd");
            //test 1000 random examples
            for (int i = 0; i < 1000; ++i)
            {
                var iTmp   = genRnd();
                var inpTmp = State.Create(grammar.Value.InputSymbol, iTmp);
                var oTmp   = add(iTmp);
                var outTmp = (double[])learnedSet.RealizedPrograms.First().Invoke(inpTmp);
                TestContext.WriteLine("Excpt [{0}]", string.Join(", ", oTmp));
                TestContext.WriteLine("Actul [{0}]", string.Join(", ", outTmp));
                Assert.AreEqual(oTmp[0], outTmp[0], 0.001d);
            }
        }
Exemplo n.º 5
0
        public static void Setup()
        {
            _grammar = LoadGrammar("TreeLang.grammar",
                                   CompilerReference.FromAssemblyFiles(
                                       typeof(Microsoft.ProgramSynthesis.Utils.Record).GetTypeInfo().Assembly,
                                       typeof(Semantics).GetTypeInfo().Assembly,
                                       typeof(SyntaxNode).GetTypeInfo().Assembly));
            if (_grammar == null)
            {
                Log.Error("Failed to compile TreeLang.grammar.");
                return;
            }

            InputSymbol = _grammar.InputSymbol;

            _scorer = new RankingScore(_grammar);
            _engine = new SynthesisEngine(_grammar, new SynthesisEngine.Config
            {
                Strategies = new ISynthesisStrategy[]
                {
                    new PremStrategy(_grammar),
                },
                UseThreads = false
            });

            Log.Debug("Transformer: synthesis engine is setup.");
        }
Exemplo n.º 6
0
        public void TestLearnSub()
        {
            var grammar = DSLCompiler.LoadGrammarFromFile("../../../ProseDSLModels.grammar");

            printGrammar(grammar);
            SynthesisEngine prose = new SynthesisEngine(grammar.Value);

            double[] inp1 = new double[4] {
                10.9, 15.0, -14.5, 12.3
            };
            double[] out1 = new double[4] {
                0.0, 4.1, -25.4, 1.4
            };
            var input = State.Create(grammar.Value.InputSymbol, inp1);

            var examples = new Dictionary <State, object> {
                { input, out1 }
            };
            var spec       = new ExampleSpec(examples);
            var learnedSet = prose.LearnGrammar(spec);
            var output     = (double[])learnedSet.RealizedPrograms.First().Invoke(input);

            Assert.AreEqual(0.0, output[0], 0.001d);
            Assert.AreEqual(4.1, output[1], 0.001d);
            Assert.AreEqual(-25.4, output[2], 0.001d);
            Assert.AreEqual(1.4, output[3], 0.001d);
        }
Exemplo n.º 7
0
        public static void RunTest()
        {
            DesignContext.Reset();
            FixedPointSettings.GlobalDefaultRadix = 10;

            var tb = new Test_SinCosLUT_Testbench(7, 8, 9, 0);

            DesignContext.Instance.Elaborate();
            DesignContext.Instance.Simulate(new Time(1.0, ETimeUnit.us));
            DesignContext.Stop();
            //XilinxIntegration.RegisterIPCores(DesignContext.Instance.Descriptor);
            DesignContext.Instance.CompleteAnalysis();

            // Now convert the design to VHDL and embed it into a Xilinx ISE project
            XilinxProject project = new XilinxProject(@".\hdl_out_Test_SinCosLUT_Testbench", "Test_SinCosLUT_Testbench");

            project.PutProperty(EXilinxProjectProperties.DeviceFamily, EDeviceFamily.Virtex6);
            project.PutProperty(EXilinxProjectProperties.Device, EDevice.xc6vlx240t);
            project.PutProperty(EXilinxProjectProperties.Package, EPackage.ff1156);
            project.PutProperty(EXilinxProjectProperties.SpeedGrade, ESpeedGrade._2);
            project.PutProperty(EXilinxProjectProperties.PreferredLanguage, EHDL.VHDL);
            project.SetVHDLProfile();
            project.TwinProject = new ModelsimProject(@".\hdl_out_Test_SinCosLUT_Testbench", "Test_SinCosLUT_Testbench");

            VHDLGenerator codeGen = new VHDLGenerator();

            SynthesisEngine.Create(DesignContext.Instance, project).Synthesize(tb, codeGen);
            project.Save();
        }
Exemplo n.º 8
0
        private static void Main(string[] args)
        {
            _prose = ConfigureSynthesis();
            var menu   = @"Select one of the options: 
1 - provide training task
2 - run top synthesized program on test
3 - exit";
            var option = 0;

            while (option != 3)
            {
                Console.Out.WriteLine(menu);
                try
                {
                    option = short.Parse(Console.ReadLine());
                }
                catch (Exception)
                {
                    Console.Out.WriteLine("Invalid option. Try again.");
                    continue;
                }

                RunOption(option);
            }
        }
Exemplo n.º 9
0
        static void Main(string[] args)
        {
            Testbench tb = new Testbench();

            DesignContext.Instance.Elaborate();
            DesignContext.Instance.Simulate(101 * Testbench.ClockPeriod);

            // Now convert the design to VHDL and embed it into a Xilinx ISE project
            XilinxProject project_SC = new XilinxProject(@".\SystemC_output", "SimpleCounter");

            project_SC.PutProperty(EXilinxProjectProperties.DeviceFamily, EDeviceFamily.Spartan3);
            project_SC.PutProperty(EXilinxProjectProperties.Device, EDevice.xc3s1500l);
            project_SC.PutProperty(EXilinxProjectProperties.Package, EPackage.fg676);
            project_SC.PutProperty(EXilinxProjectProperties.SpeedGrade, ESpeedGrade._4);
            project_SC.PutProperty(EXilinxProjectProperties.PreferredLanguage, EHDL.VHDL);

            SystemCGenerator codeGen_SC = new SystemCGenerator();

            SynthesisEngine.Create(DesignContext.Instance, project_SC).Synthesize(codeGen_SC);
            project_SC.Save();

            DesignContext.Instance.CompleteAnalysis();

            // The actual compilation steps start here.
            ProcessDescriptor euclid = tb.Descriptor.FindComponent("_gcd").FindProcess("Euclid");
            XIL3Function      asm    = euclid.Implementation.Compile(DefaultInstructionSet.Instance).ToXIL3();

            Console.WriteLine(asm);
        }
Exemplo n.º 10
0
        public void TestLearnSubstringPositiveAbsPos()
        {
            //parse grammar file
            Result <Grammar> grammar = CompileGrammar();
            //configure the prose engine
            SynthesisEngine prose = ConfigureSynthesis(grammar.Value);

            //create the example
            State input    = State.CreateForExecution(grammar.Value.InputSymbol, "19-Feb-1960");
            var   examples = new Dictionary <State, object> {
                { input, "Feb" }
            };
            var spec = new ExampleSpec(examples);

            //learn the set of programs that satisfy the spec
            ProgramSet learnedSet = prose.LearnGrammar(spec);

            //run the first synthesized program in the same input and check if
            //the output is correct
            IEnumerable <ProgramNode> programs = learnedSet.RealizedPrograms;
            var output = programs.First().Invoke(input) as string;

            Assert.AreEqual("Feb", output);

            State differentInput = State.CreateForExecution(grammar.Value.InputSymbol, "15-Jan-2000");

            output = programs.First().Invoke(differentInput) as string;
            Assert.AreEqual("Jan", output);
        }
Exemplo n.º 11
0
        public void TestLearnSubstringTwoExamples()
        {
            Result <Grammar> grammar = CompileGrammar();
            SynthesisEngine  prose   = ConfigureSynthesis(grammar.Value);

            State firstInput  = State.CreateForExecution(grammar.Value.InputSymbol, "Toby Miller");
            State secondInput = State.CreateForExecution(grammar.Value.InputSymbol, "Courtney Lynch");
            var   examples    = new Dictionary <State, object> {
                { firstInput, "Miller" }, { secondInput, "Lynch" }
            };
            var spec = new ExampleSpec(examples);

            ProgramSet learnedSet = prose.LearnGrammar(spec);
            IEnumerable <ProgramNode> programs = learnedSet.RealizedPrograms;
            var output = programs.First().Invoke(firstInput) as string;

            Assert.AreEqual("Miller", output);
            var output2 = programs.First().Invoke(secondInput) as string;

            Assert.AreEqual("Lynch", output2);
            State differentInput = State.CreateForExecution(grammar.Value.InputSymbol, "Yun Jasinska");

            output = programs.First().Invoke(differentInput) as string;
            Assert.AreEqual("Jasinska", output);
        }
Exemplo n.º 12
0
        public static ProgramNode Learn(Grammar grammar, Spec spec,
                                        Feature <double> scorer, DomainLearningLogic witnessFunctions)
        {
            var engine = new SynthesisEngine(grammar, new SynthesisEngine.Config
            {
                Strategies = new ISynthesisStrategy[]
                {
                    new EnumerativeSynthesis(),
                    new DeductiveSynthesis(witnessFunctions)
                },
                UseThreads  = false,
                LogListener = new LogListener(),
            });
            ProgramSet consistentPrograms = engine.LearnGrammar(spec);

            engine.Configuration.LogListener.SaveLogToXML("learning.log.xml");

            //foreach (ProgramNode p in consistentPrograms.RealizedPrograms) {
            //    Console.WriteLine(p);
            //}

            ProgramNode bestProgram = consistentPrograms.TopK(scorer).FirstOrDefault();

            if (bestProgram == null)
            {
                WriteColored(ConsoleColor.Red, "No program :(");
                return(null);
            }
            var score = bestProgram.GetFeatureValue(scorer);

            WriteColored(ConsoleColor.Cyan, $"[score = {score:F3}] {bestProgram}");
            return(bestProgram);
        }
Exemplo n.º 13
0
        public static ProgramSet Learn(Grammar g, Spec s, string logXmlFilename)
        {
            var engine = new SynthesisEngine(
                grammar: g,
                config: new SynthesisEngine.Config
            {
                Strategies = new ISynthesisStrategy[]
                {
                    new EnumerativeSynthesis(
                        new EnumerativeSynthesis.Config
                    {
                        MaximalSize = 101 * 101 * 11 * 2
                    }
                        ),
                    new ComponentBasedSynthesis(null, null, null)
                },
                UseThreads  = true,
                LogListener = new LogListener()
            });

            var consistentPrograms = engine.LearnGrammar(s);

            engine.Configuration.LogListener.SaveLogToXML(logXmlFilename);

            return(consistentPrograms);
        }
Exemplo n.º 14
0
        private static void Main(string[] args)
        {
            _prose = ConfigureSynthesis();
            var menu   = @"Select one of the options: 
1 - provide new example
2 - run top synthesized program on a new input
3 - exit";
            var option = 0;

            while (option != 3)
            {
                Console.Out.WriteLine(menu);
                try
                {
                    option = short.Parse(Console.ReadLine());
                }
                catch (Exception)
                {
                    Console.Out.WriteLine("Invalid option. Try again.");
                    continue;
                }

                try
                {
                    RunOption(option);
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine("Something went wrong...");
                    Console.Error.WriteLine("Exception message: {0}", e.Message);
                }
            }
        }
Exemplo n.º 15
0
        public static void RunTest()
        {
            DesignContext.Reset();

            TestDesign1 td1 = new TestDesign1(3, 4);

            FixedPointSettings.GlobalOverflowMode = EOverflowMode.Wrap;
            DesignContext.Instance.Elaborate();
            DesignContext.Instance.Simulate(20 * TestDesign1.ClockPeriod);

            // Now convert the design to VHDL and embed it into a Xilinx ISE project
            XilinxProject project = new XilinxProject(@".\hdl_TestDesign1", "TestDesign1");

            project.PutProperty(EXilinxProjectProperties.DeviceFamily, EDeviceFamily.Spartan3);
            project.PutProperty(EXilinxProjectProperties.Device, EDevice.xc3s1500l);
            project.PutProperty(EXilinxProjectProperties.Package, EPackage.fg676);
            project.PutProperty(EXilinxProjectProperties.SpeedGrade, ESpeedGrade._4);
            project.PutProperty(EXilinxProjectProperties.PreferredLanguage, EHDL.VHDL);

            VHDLGenerator codeGen = new VHDLGenerator();

            SynthesisEngine.Create(DesignContext.Instance, project).Synthesize(codeGen);;
            project.Save();

            DesignContext.Reset();
        }
Exemplo n.º 16
0
        static void Main(string[] args)
        {
            Testbench tb = new Testbench();

            DesignContext.Instance.Elaborate();
            DesignContext.Instance.Simulate(10 * (Design.DataWidth + 3) * Testbench.ClockPeriod);
            //Console.Read();

#if RUNANALYSIS
            // Now convert the design to VHDL and embed it into a Xilinx ISE project
            XilinxProject project = new XilinxProject(@".\hdl_output", "BitSerializer");
            project.PutProperty(EXilinxProjectProperties.DeviceFamily, EDeviceFamily.Spartan3);
            project.PutProperty(EXilinxProjectProperties.Device, EDevice.xc3s1500l);
            project.PutProperty(EXilinxProjectProperties.Package, EPackage.fg676);
            project.PutProperty(EXilinxProjectProperties.SpeedGrade, ESpeedGrade._4);
            project.PutProperty(EXilinxProjectProperties.PreferredLanguage, EHDL.VHDL);

            VHDLGenerator codeGen = new VHDLGenerator();
            SynthesisEngine.Create(DesignContext.Instance, project).Synthesize(codeGen);
            project.Save();

            //// Now convert the design to VHDL and embed it into a Xilinx ISE project
            //XilinxProject project_SC = new XilinxProject(@".\SystemC_output", "SimpleCounter");
            //project_SC.PutProperty(EXilinxProjectProperties.DeviceFamily, EDeviceFamily.Spartan3);
            //project_SC.PutProperty(EXilinxProjectProperties.Device, EDevice.xc3s1500l);
            //project_SC.PutProperty(EXilinxProjectProperties.Package, EPackage.fg676);
            //project_SC.PutProperty(EXilinxProjectProperties.SpeedGrade, ESpeedGrade._4);
            //project_SC.PutProperty(EXilinxProjectProperties.PreferredLanguage, EHDL.VHDL);

            //SystemCGenerator codeGen_SC = new SystemCGenerator();
            //SynthesisEngine.Create(DesignContext.Instance, project_SC).Synthesize(codeGen_SC);
            //project_SC.Save();
#endif
        }
Exemplo n.º 17
0
        public static void RunTest()
        {
            DesignContext.Reset();

            TestHLS_PortAccess_Testbench tb = new TestHLS_PortAccess_Testbench();

            DesignContext.Instance.Elaborate();
            DesignContext.Instance.Simulate(new Time(1.0, ETimeUnit.us));
            DesignContext.Stop();
            DesignContext.Instance.CompleteAnalysis();

            // Now convert the design to VHDL and embed it into a Xilinx ISE project
            XilinxProject project = new XilinxProject(@".\hdl_out_TestHLS_PortAccess", "TestHLS_PortAccess");

            project.PutProperty(EXilinxProjectProperties.DeviceFamily, EDeviceFamily.Virtex6);
            project.PutProperty(EXilinxProjectProperties.Device, EDevice.xc6vlx240t);
            project.PutProperty(EXilinxProjectProperties.Package, EPackage.ff1156);
            project.PutProperty(EXilinxProjectProperties.SpeedGrade, ESpeedGrade._2);
            project.PutProperty(EXilinxProjectProperties.PreferredLanguage, EHDL.VHDL);
            project.SetVHDLProfile();
            project.SkipIPCoreSynthesis = true;

            VHDLGenerator codeGen = new VHDLGenerator();

            SynthesisEngine.Create(DesignContext.Instance, project).Synthesize(tb, codeGen);
            project.Save();
        }
Exemplo n.º 18
0
        public static ProgramNode Learn(Grammar grammar, Spec spec)
        {
            var engine = new SynthesisEngine(grammar, new SynthesisEngine.Config
            {
                UseThreads  = false,
                LogListener = new LogListener(),
            });
            ProgramSet consistentPrograms = engine.LearnGrammar(spec);

            engine.Configuration.LogListener.SaveLogToXML("learning.log.xml");

            //foreach (ProgramNode p in consistentPrograms.RealizedPrograms) {
            //    Console.WriteLine(p);
            //}

            ProgramNode bestProgram = consistentPrograms.TopK("Score").FirstOrDefault();

            if (bestProgram == null)
            {
                WriteColored(ConsoleColor.Red, "No program :(");
                return(null);
            }
            var score = bestProgram["Score"];

            WriteColored(ConsoleColor.Cyan, $"[score = {score:F3}] {bestProgram}");
            return(bestProgram);
        }
Exemplo n.º 19
0
        public static void RunTest()
        {
            DesignContext.Reset();

            TestHLS_CordicSqrt_Testbench tb = new TestHLS_CordicSqrt_Testbench();

            DesignContext.Instance.Elaborate();
            DesignContext.Instance.Simulate(new Time(100.0, ETimeUnit.us));
            DesignContext.Stop();
            XilinxIntegration.RegisterIPCores(DesignContext.Instance.Descriptor);
            DesignContext.Instance.CompleteAnalysis();

            // Now convert the design to VHDL and embed it into a Xilinx ISE project
            var docproj = new DocumentationProject(@".\hdl_out_TestHLSSqrt_Cordic\doc");
            var project = new XilinxProject(@".\hdl_out_TestHLSSqrt_Cordic", "TestHLSSqrt_Cordic");

            project.ISEVersion = EISEVersion._13_2;
            project.PutProperty(EXilinxProjectProperties.DeviceFamily, EDeviceFamily.Virtex6);
            project.PutProperty(EXilinxProjectProperties.Device, EDevice.xc6vlx240t);
            project.PutProperty(EXilinxProjectProperties.Package, EPackage.ff1156);
            project.PutProperty(EXilinxProjectProperties.SpeedGrade, ESpeedGrade._2);
            project.PutProperty(EXilinxProjectProperties.PreferredLanguage, EHDL.VHDL);
            project.SetVHDLProfile();
            //project.SkipIPCoreSynthesis = true;

            VHDLGenerator codeGen = new VHDLGenerator();

            SynthesisEngine.Create(DesignContext.Instance, project).Synthesize(tb, codeGen);
            SynthesisEngine.Create(DesignContext.Instance, docproj).Synthesize(new DocumentationGenerator());
            project.Save();
            docproj.Save();
        }
Exemplo n.º 20
0
        public void TestLearnSubstringOneExample()
        {
            Result <Grammar> grammar = CompileGrammar();
            SynthesisEngine  prose   = ConfigureSynthesis(grammar.Value);

            State input    = State.CreateForExecution(grammar.Value.InputSymbol, "Toby Miller");
            var   examples = new Dictionary <State, object> {
                { input, "Miller" }
            };

            var spec = new ExampleSpec(examples);

            var         scoreFeature = new RankingScore(grammar.Value);
            ProgramSet  topPrograms  = prose.LearnGrammarTopK(spec, scoreFeature, 1, null);
            ProgramNode topProgram   = topPrograms.RealizedPrograms.First();

            var x = topProgram.PrintAST();
            var y = ProgramNode.Parse(x, grammar.Value); // var y is null. ==> SDK method

            var se = new ASTSerialization.Serialization(grammar.Value);
            var xe = se.PrintXML(topProgram);

            xe.Save(SavedProgramAST);
            topProgram = se.Parse(xe); // var topProgram is ok. ==> ASTSerialization.Serialization method

            var output = topProgram.Invoke(input) as string;

            Assert.AreEqual("Miller", output);

            State input2  = State.CreateForExecution(grammar.Value.InputSymbol, "Courtney Lynch");
            var   output2 = topProgram.Invoke(input2) as string;

            Assert.AreEqual("Lynch", output2);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Entry point of the synthesis strategy, implementing
        /// `Microsoft.ProgramSynthesis.Learning.Strategies.SynthesisStrategy`.
        /// </summary>
        /// <param name="engine">Synthesis engine.</param>
        /// <param name="task">Learning task, which contains the specification.</param>
        /// <param name="cancel">Cancellation token.</param>
        /// <returns></returns>
        public override Optional <ProgramSet> Learn(SynthesisEngine engine, LearningTask <ExampleSpec> task,
                                                    CancellationToken cancel)
        {
            var spec       = task.Spec;
            var programSet = LearnProgram(
                PremSpec <TInput, SyntaxNode> .From(spec.Examples, GetInput, o => (SyntaxNode)o));

            return(programSet);
        }
Exemplo n.º 22
0
 public Refazer4Python(string pathToGrammar = @"..\..\..\Tutor\synthesis\", string pathToDslLib = @"..\..\..\Tutor\bin\debug")
 {
     _pathToGrammar = pathToGrammar;
     _pathToDslLib  = pathToDslLib;
     Grammar        = DSLCompiler.LoadGrammarFromFile(pathToGrammar + @"Transformation.grammar",
                                                      libraryPaths: new[] { pathToDslLib });
     _prose = new SynthesisEngine(Grammar.Value,
                                  new SynthesisEngine.Config {
         LogListener = new LogListener()
     });
 }
Exemplo n.º 23
0
        public static SynthesisEngine ConfigureSynthesis(Grammar grammar)
        {
            var witnessFunctions     = new WitnessFunctions(grammar);
            var deductiveSynthesis   = new DeductiveSynthesis(witnessFunctions);
            var synthesisExtrategies = new ISynthesisStrategy[] { deductiveSynthesis };
            var synthesisConfig      = new SynthesisEngine.Config {
                Strategies = synthesisExtrategies
            };
            var prose = new SynthesisEngine(grammar, synthesisConfig);

            return(prose);
        }
Exemplo n.º 24
0
        /// <summary>
        ///     Learn <paramref name="k" /> top-ranked Transformation.Text programs for a given set of input-output examples.
        /// </summary>
        /// <param name="trainingExamples">
        ///     The set of input-output examples as a Tuple of the input and the output.
        /// </param>
        /// <param name="additionalInputs">
        ///     The set of additional inputs that do not have output examples, which helps rank learnt programs.
        /// </param>
        /// <param name="k">the number of top programs</param>
        /// <returns>The top-k ranked programs as <see cref="TextTransformationProgram" />s</returns>
        public static IEnumerable <TextTransformationProgram> LearnTopK(IDictionary <string, string> trainingExamples,
                                                                        IEnumerable <string> additionalInputs = null,
                                                                        int k = 1)
        {
            if (trainingExamples == null)
            {
                throw new ArgumentNullException(nameof(trainingExamples));
            }
            // Load Transformation.Text grammar
            Grammar             grammar       = Language.Grammar;
            DomainLearningLogic learningLogic = new Witnesses(grammar,
                                                              // This is currently required as a workaround for a bug.
                                                              ((RankingScore)Learner.Instance.ScoreFeature).Clone());

            // Setup configuration of synthesis process.
            var engine = new SynthesisEngine(grammar, new SynthesisEngine.Config
            {
                // Strategies perform the actual logic of the synthesis process.
                Strategies = new[] { new DeductiveSynthesis(learningLogic) },
                UseThreads = false,
                CacheSize  = int.MaxValue
            });
            // Convert the examples in the format expected by Microsoft.ProgramSynthesis.
            // Internally, Transformation.Text represents strings as ValueSubstrings to save on
            //  allocating new strings for each substring.
            // Could also use InputRow.AsState() to construct the input state.
            Dictionary <State, object> trainExamples = trainingExamples.ToDictionary(
                t => State.Create(grammar.InputSymbol, new[] { ValueSubstring.Create(t.Key) }),
                t => (object)ValueSubstring.Create(t.Value));
            var spec = new ExampleSpec(trainExamples);
            // Learn an entire Transformation.Text program (i.e. start at the grammar's start symbol)
            //  for the specification consisting of the examples.
            // Learn the top-k programs according to the score feature used by Transformation.Text by default.
            // You could define your own feature on the Transformation.Text grammar to rank programs differently.
            var task = new LearningTask(grammar.StartSymbol, spec, k, Learner.Instance.ScoreFeature);

            if (additionalInputs != null)
            {
                task.AdditionalInputs =
                    additionalInputs.Select(
                        input =>
                        State.Create(grammar.InputSymbol, new[] { ValueSubstring.Create(input) }))
                    .ToList();
            }
            IEnumerable <ProgramNode> topk = engine.Learn(task).RealizedPrograms;

            // Return the generated programs wraped in a TextTransformationProgram object.
            return(topk.Select(prog => new TextTransformationProgram(prog)));
        }
Exemplo n.º 25
0
        public static void RunTest()
        {
            DesignContext.Reset();
            Testbench tb = new Testbench();

            DesignContext.Instance.Elaborate();
            DesignContext.Instance.Simulate(101 * Testbench.ClockPeriod);
            DesignContext.Instance.CompleteAnalysis();

            VHDLGenerator        codeGen = new VHDLGenerator();
            DocumentationProject proj    = new DocumentationProject("./doc");

            SynthesisEngine.Create(DesignContext.Instance, proj).Synthesize(codeGen);
            proj.Save();
        }
Exemplo n.º 26
0
        static ProgramNode learnFromExamples(Grammar grammar, SynthesisEngine engine, RankingScore rankingScores, Dictionary <string, string> exs)
        {
            var spec = toSpec(grammar, exs);
            var ps   = engine.LearnGrammar(spec);

            Console.WriteLine("all programs: " + ps);
            var best = ps.TopK(rankingScores).First();

            Console.WriteLine("best program: " + best);
            foreach (var ex in spec.Examples)
            {
                System.Diagnostics.Debug.Assert(best.Invoke(ex.Key).Equals(ex.Value));
            }
            return(best);
        }
Exemplo n.º 27
0
            static void Main(string[] args)
            {
                ///default values
                int cycles = 100;

                FixedPointSettings.GlobalDefaultRadix = 10;
                FixedPointSettings.GlobalOverflowMode = EOverflowMode.Fail;

                ///elaborate
                SimpleCounterTestbench tb = new SimpleCounterTestbench();

                DesignContext.Instance.Elaborate();

                ///print out config
                Console.WriteLine("#cycles: " + cycles);

                ///simulate
                DesignContext.Instance.Simulate(cycles * SimpleCounterTestbench.ClockPeriod);

                ///notify completion
                Console.WriteLine("Done.  [ #cycles = " + cycles + " ]");


#if RUNANALYSIS
                // Now convert the design to VHDL and embed it into a Xilinx ISE project
                XilinxProject project = new XilinxProject(@".\hdl_output", "SimpleCounter");
                project.PutProperty(EXilinxProjectProperties.DeviceFamily, EDeviceFamily.Spartan3);
                project.PutProperty(EXilinxProjectProperties.Device, EDevice.xc3s1500l);
                project.PutProperty(EXilinxProjectProperties.Package, EPackage.fg676);
                project.PutProperty(EXilinxProjectProperties.SpeedGrade, ESpeedGrade._4);
                project.PutProperty(EXilinxProjectProperties.PreferredLanguage, EHDL.VHDL);

                VHDLGenerator codeGen = new VHDLGenerator();
                SynthesisEngine.Create(DesignContext.Instance, project).Synthesize(codeGen);
                project.Save();

                //XilinxProject project_SC = new XilinxProject(@".\SystemC_output", "SimpleCounter");
                //project_SC.PutProperty(EXilinxProjectProperties.DeviceFamily, EDeviceFamily.Spartan3);
                //project_SC.PutProperty(EXilinxProjectProperties.Device, EDevice.xc3s1500l);
                //project_SC.PutProperty(EXilinxProjectProperties.Package, EPackage.fg676);
                //project_SC.PutProperty(EXilinxProjectProperties.SpeedGrade, ESpeedGrade._4);
                //project_SC.PutProperty(EXilinxProjectProperties.PreferredLanguage, EHDL.VHDL);

                //SystemCGenerator codeGen_SC = new SystemCGenerator();
                //SynthesisEngine.Create(DesignContext.Instance, project_SC).Synthesize(codeGen_SC);
                //project_SC.Save();
#endif
            }
Exemplo n.º 28
0
        private ProgramSet LearnProgramSet(Spec spec, DomainLearningLogic witnessFunctions)
        {
            var engine = new SynthesisEngine(Grammar, new SynthesisEngine.Config
            {
                Strategies = new ISynthesisStrategy[] {
                    new EnumerativeSynthesis(),
                    new DeductiveSynthesis(witnessFunctions)
                },
                UseThreads  = false,
                LogListener = new LogListener(),
            });
            ProgramSet consistentPrograms = engine.LearnGrammar(spec);

            engine.Configuration.LogListener.SaveLogToXML("learning.log.xml");
            return(consistentPrograms);
        }
Exemplo n.º 29
0
        public IEnumerable <Transformation> LearnTransformations(List <Tuple <string, string> > examples,
                                                                 int numberOfPrograms = 1, string ranking = "specific")
        {
            var spec = CreateExampleSpec(examples);

            //TODO: this is not thread safe. If multiple instances of Refazer are changing
            //the value of the ranking scores, we can have a problem.
            RankingScore.ScoreForContext = ranking.Equals("specific") ? 100 : -100;
            var scoreFeature = new RankingScore(Grammar.Value);
            DomainLearningLogic learningLogic = new WitnessFunctions(Grammar.Value);

            _prose = new SynthesisEngine(Grammar.Value,
                                         new SynthesisEngine.Config
            {
                LogListener = new LogListener(),
                Strategies  = new[] { new DeductiveSynthesis(learningLogic) },
                UseThreads  = false,
                CacheSize   = int.MaxValue
            });

            var learned = _prose.LearnGrammarTopK(spec, scoreFeature, 1);

            var uniqueTransformations = new List <ProgramNode>();

            //filter repetitive transformations
            foreach (var programNode in learned)
            {
                var exists = false;
                foreach (var uniqueTransformation in uniqueTransformations)
                {
                    if (programNode.ToString().Equals(uniqueTransformation.ToString()))
                    {
                        exists = true;
                        break;
                    }
                }
                if (!exists)
                {
                    uniqueTransformations.Add(programNode);
                }
            }
            uniqueTransformations = uniqueTransformations.Count > numberOfPrograms
                ? uniqueTransformations.GetRange(0, numberOfPrograms)
                : uniqueTransformations;

            return(uniqueTransformations.Select(e => new PythonTransformation(e)));
        }
Exemplo n.º 30
0
        public static ProgramSet LearnDeductively(Grammar g, Spec s, DomainLearningLogic witness, string logXmlFilename)
        {
            var engine = new SynthesisEngine(
                grammar: g,
                config: new SynthesisEngine.Config
            {
                Strategies  = new[] { new DeductiveSynthesis(witness) },
                UseThreads  = true,
                LogListener = new LogListener()
            }
                );
            var consistentPrograms = engine.LearnGrammar(s);

            engine.Configuration.LogListener.SaveLogToXML(logXmlFilename);

            return(consistentPrograms);
        }
Exemplo n.º 31
0
    static void testSynthesis(Grammar grammar, Dictionary<State, object> examples)
    {
        var spec = new ExampleSpec(examples);
        var engine = new SynthesisEngine(grammar);
        ProgramSet learned = engine.LearnGrammar(spec);

        Console.WriteLine("Examples:");
        foreach (KeyValuePair<State, object> ex in examples)
            Console.WriteLine("(Input: " + ex.Key + ", Output: " + ex.Value + ")");

        Console.WriteLine("These are the programs that I learned");
        foreach (ProgramNode p in learned.RealizedPrograms)
        {
            Console.WriteLine(p);
            foreach (State inputExample in examples.Keys)
            {
                Console.WriteLine("Test: (Input: " + inputExample + ", Output: " + p.Invoke(inputExample) + ")");
            }
        }
        Console.WriteLine();

    }
Exemplo n.º 32
0
        public static ProgramNode Learn(Grammar grammar, Spec spec)
        {
            var engine = new SynthesisEngine(grammar, new SynthesisEngine.Config
            {
                UseThreads = false,
                LogListener = new LogListener(),
            });
            ProgramSet consistentPrograms = engine.LearnGrammar(spec);
            engine.Configuration.LogListener.SaveLogToXML("learning.log.xml");

            //foreach (ProgramNode p in consistentPrograms.RealizedPrograms) {
            //    Console.WriteLine(p);
            //}

            ProgramNode bestProgram = consistentPrograms.TopK("Score").FirstOrDefault();
            if (bestProgram == null)
            {
                WriteColored(ConsoleColor.Red, "No program :(");
                return null;
            }
            var score = bestProgram["Score"];
            WriteColored(ConsoleColor.Cyan, $"[score = {score:F3}] {bestProgram}");
            return bestProgram;
        }