Esempio n. 1
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.");
        }
Esempio n. 2
0
        private static void LearnPrograms()
        {
            var spec = new ExampleSpec(examples);

            Console.Out.WriteLine("Learning a program for examples: ");

            foreach (var example in examples)
            {
                Console.WriteLine("\"" + example.Key.Bindings.First().Value + "\" -> \"" + example.Value + "\"");
            }

            var scoreFeature = new RankingScore(grammar);
            var topPrograms  = prose.LearnGrammarTopK(spec, scoreFeature, 4, null);

            if (topPrograms.IsEmpty())
            {
                throw new Exception("No program was found for this specification.");
            }

            topProgram = topPrograms.First();
            Console.Out.WriteLine("Top 4 learned programs: ");

            foreach (var program in topPrograms)
            {
                Console.Out.WriteLine("-----------------------------");
                Console.Out.WriteLine(program.PrintAST(Microsoft.ProgramSynthesis.AST.ASTSerializationFormat.HumanReadable));
            }
        }
Esempio n. 3
0
        private static void LearnFromNewExample()
        {
            Console.Out.Write("Provide a new input-output example as \"input\", \"output\":\n");
            try
            {
                string input              = Console.ReadLine();
                var    startFirstExample  = input.IndexOf("\"") + 1;
                var    endFirstExample    = input.IndexOf("\"", startFirstExample + 1) + 1;
                var    startSecondExample = input.IndexOf("\"", endFirstExample + 1) + 1;
                var    endSecondExample   = input.IndexOf("\"", startSecondExample + 1) + 1;

                if ((startFirstExample >= endFirstExample) || (startSecondExample >= endSecondExample))
                {
                    throw new Exception("Invalid example format. Please try again. input and out should be between quotes");
                }

                var inputExample  = input.Substring(startFirstExample, endFirstExample - startFirstExample - 1);
                var outputExample = input.Substring(startSecondExample, endSecondExample - startSecondExample - 1);

                var inputState = State.CreateForExecution(grammar.InputSymbol, inputExample);
                examples.Add(inputState, outputExample);
            } catch (Exception)
            {
                throw new Exception("Invalid example format. Please try again. input and out should be between quotes");
            }

            var spec = new ExampleSpec(examples);

            Console.Out.WriteLine("Learning a program for examples:");
            foreach (var example in examples)
            {
                Console.WriteLine("\"" + example.Key.Bindings.First().Value + "\" -> \"" + example.Value + "\"");
            }

            var        scoreFeature = new RankingScore(grammar);
            ProgramSet topPrograms  = prose.LearnGrammarTopK(spec, scoreFeature, 4, null);

            if (topPrograms.IsEmpty)
            {
                throw new Exception("No program was found for this specification.");
            }

            topProgram = topPrograms.RealizedPrograms.First();
            Console.Out.WriteLine("Top 4 learned programs:");
            var counter = 1;

            foreach (var program in topPrograms.RealizedPrograms)
            {
                if (counter > 4)
                {
                    break;
                }
                Console.Out.WriteLine("==========================");
                Console.Out.WriteLine("Program " + counter + ": ");
                Console.Out.WriteLine(program.PrintAST(Microsoft.ProgramSynthesis.AST.ASTSerializationFormat.HumanReadable));
                counter++;
            }
        }
Esempio n. 4
0
 void Update()
 {
     if (flag == false)
     {
         flag      = true;
         total     = Score_picture.picture_p + Score_time.sum;
         text.text = total.ToString("0");
         RankingScore.Judge(total);
     }
 }
Esempio n. 5
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)));
        }
Esempio n. 6
0
        public ActionResult LearnTransformation([FromBody] LearnTransformRequestBody requestBody)
        {
            try
            {
                Console.WriteLine(requestBody.Instance);

                ProgramSet learned;
                using (var ctx = new Context())
                {
                    var inputExamples = Utils.GetInputOutputExamplesModified(ctx, requestBody.InputOutputExamples,
                                                                             SmtPrefix, requestBody.DeclareStatements);
                    var spec = Utils.CreateExampleSpec(_grammar, inputExamples);
                    RankingScore.ScoreForContext = 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 ISynthesisStrategy[] { new DeductiveSynthesis(learningLogic) },
                        UseThreads  = false,
                        CacheSize   = int.MaxValue
                    });
                    learned = _prose.LearnGrammarTopK(spec, scoreFeature);
                }

                var finalPrograms = learned.RealizedPrograms.Select(program => new FinalProgram(program.ToString(), program.PrintAST())).ToList();
                if (finalPrograms.Count == 0)
                {
                    Console.WriteLine("No Programs Found");
                }

                foreach (var program in finalPrograms)
                {
                    Console.WriteLine(program.HumanReadableAst);
                }
                return(Ok(JsonConvert.SerializeObject(finalPrograms)));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
                Console.WriteLine(ex.TargetSite);
                Console.WriteLine("Error: " + ex.Message);
                return(StatusCode(500, ex.Message));
            }
        }
Esempio n. 7
0
        public static void Main(string[] args)
        {
            var grammar       = getGrammar();
            var engine        = getEngine(grammar);
            var rankingScores = new RankingScore(grammar);

            Console.WriteLine("1");
            learnFromExamples(grammar, engine, rankingScores, new Dictionary <string, string> {
                ["c"] = "(a b)"
            });
            Console.WriteLine("2");
            learnFromExamples(grammar, engine, rankingScores, new Dictionary <string, string>
            {
                ["(a b)"] = "a"
            });
            Console.WriteLine("3");
            learnFromExamples(grammar, engine, rankingScores, new Dictionary <string, string>
            {
                ["(a b)"]   = "a",
                ["(a1 b1)"] = "a1"
            });
            Console.WriteLine("4");
            learnFromExamples(grammar, engine, rankingScores, new Dictionary <string, string>
            {
                ["(a b)"] = "b"
            });
            Console.WriteLine("5");
            learnFromExamples(grammar, engine, rankingScores, new Dictionary <string, string>
            {
                ["a"] = "(a a)"
            });
            Console.WriteLine("6");
            learnFromExamples(grammar, engine, rankingScores, new Dictionary <string, string>
            {
                ["(a b)"]   = "((a b) (b a))",
                ["(a1 b1)"] = "((a1 b1) (b1 a1))"
            });
        }
Esempio n. 8
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);
        }