Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
01/14/14 12:40:26 (11 years ago)
Author:
gkronber
Message:

#2026 worked on code generator for random search (work in progress commit)

File:
1 edited

Legend:

Unmodified
Added
Removed
  • branches/HeuristicLab.Problems.GPDL/CodeGenerator/ProblemCodeGen.cs

    r10100 r10335  
    1818    private const string problemTemplate = @"
    1919namespace ?PROBLEMNAME? {
    20   public interface IGpdlProblem {
    21     int GetCardinality(string terminalSymbol, string attribute);
    22   }
     20
     21  // generic interface for communication from problem interpretation to solver
    2322  public interface ISolverState {
    2423    void Reset();
    25     int PeekNextAlternative();
    26     void Follow(int idx);
    27     void Unwind();
     24    int PeekNextAlternative(); // in alternative nodes returns the index of the alternative that should be followed
     25    void Follow(int idx); // next: derive the NT symbol with index=idx;
     26    void Unwind(); // finished with deriving the NT symbol
    2827  }
    2928
    30   public sealed class ?IDENT?Problem : IGpdlProblem {
     29  public sealed class ?IDENT?Problem {
    3130   
    32    private readonly Dictionary<string, Dictionary<string, int>> cardinalities = new Dictionary<string, Dictionary<string, int>>();
    3331   public ?IDENT?Problem() {
    3432      Initialize();
    35 
    36 ?CONSTRUCTORSOURCE?
    37 
    3833    }   
    3934
    4035    private void Initialize() {
     36      // the following is the source code from the INIT section of the problem definition
     37#region INIT section
    4138?INITSOURCE?
     39#endregion
    4240    }
    4341
     
    4543    public double Evaluate(ISolverState _state) {
    4644      this._state = _state;
     45#region objective function (MINIMIZE / MAXIMIZE section)
    4746?FITNESSFUNCTION?
    48     }
    49 
     47#endregion
     48    }
     49
     50// additional code from the problem definition (CODE section)
     51#region additional code
    5052?ADDITIONALCODE?
    51 
     53#endregion
     54
     55#region generated source for interpretation
    5256?INTERPRETERSOURCE?
    53 
     57#endregion
     58
     59#region generated code for the constraints for terminals
    5460?CONSTRAINTSSOURCE?
    55 
    56     public int GetCardinality(string terminal, string attribute) {
    57       return cardinalities[terminal][attribute];
    58     }
     61#endregion
    5962  }
    6063}";
     
    7679        .Replace("?IDENT?", ast.Name);
    7780
    78 
    7981      // write the source file to disk
    8082      using (var stream = new StreamWriter(ast.Name + ".cs")) {
     
    8890        .AppendLine(problemTemplate)
    8991        .Replace("?FITNESSFUNCTION?", ast.FitnessFunctionNode.SrcCode)
    90         .Replace("?CONSTRUCTORSOURCE?", GenerateConstructorSource(ast))
    9192        .Replace("?INITSOURCE?", ast.InitCodeNode.SrcCode)
    9293        .Replace("?ADDITIONALCODE?", ast.ClassCodeNode.SrcCode)
     
    99100      var grammar = CreateGrammarFromAst(ast);
    100101      var randomSearchCodeGen = new RandomSearchCodeGen();
    101       randomSearchCodeGen.Generate(grammar, ast.FitnessFunctionNode.Maximization, ast.Terminals, solverSourceCode);
     102      randomSearchCodeGen.Generate(grammar, ast.Terminals.OfType<TerminalNode>(), ast.FitnessFunctionNode.Maximization, solverSourceCode);
     103      //var bruteForceSearchCodeGen = new BruteForceCodeGen();
     104      //bruteForceSearchCodeGen.Generate(grammar, ast.FitnessFunctionNode.Maximization, solverSourceCode);
    102105    }
    103106
    104107    #region create grammar instance from AST
     108    // should be refactored so that we can directly query the AST
    105109    private AttributedGrammar CreateGrammarFromAst(GPDefNode ast) {
    106110
     
    131135    private IEnumerable<IAttribute> GetSymbolAttributes(string formalParameters) {
    132136      return (from fieldDef in Util.ExtractParameters(formalParameters)
    133               select new Attribute(fieldDef.Identifier, fieldDef.Type, AttributeType.Parse(fieldDef.RefOrOut))).
    134         ToList();
     137              select new Attribute(fieldDef.Identifier, fieldDef.Type, AttributeType.Parse(fieldDef.RefOrOut)))
     138              .ToList();
    135139    }
    136140
     
    178182          sb.AppendFormat("public {0} GetMax{1}_{2}() {{ return {3}; }}", fieldType, t.Ident, c.Ident, c.RangeMaxExpression).AppendLine();
    179183          sb.AppendFormat("public {0} GetMin{1}_{2}() {{ return {3}; }}", fieldType, t.Ident, c.Ident, c.RangeMinExpression).AppendLine();
    180           // sb.AppendFormat("public {0} Get{1}_{2}(ISolverState _state) {{ return _state.random.NextDouble() * (GetMax{1}_{2}() - GetMin{1}_{2}()) + GetMin{1}_{2}(); }}", fieldType, t.Ident, c.Ident).AppendLine();
    181           sb.AppendFormat("public {0} Get{1}_{2}(ISolverState _state) {{ throw new NotSupportedException(\"range constraints for terminals are not supported.\"); }}", fieldType, t.Ident, c.Ident).AppendLine();
     184          //sb.AppendFormat("public {0} Get{1}_{2}(ISolverState _state) {{ _state. }}", fieldType, t.Ident, c.Ident, )
    182185        } else if (c.Type == ConstraintNodeType.Set) {
    183186          sb.AppendFormat("public IEnumerable<{0}> GetAllowed{1}_{2}() {{ return {3}; }}", fieldType, t.Ident, c.Ident, c.SetExpression).AppendLine();
    184           sb.AppendFormat("private readonly {0}[] values_{1}_{2};", fieldType, t.Ident, c.Ident).AppendLine();
    185           sb.AppendFormat("public {0} Get{1}_{2}(ISolverState _state) {{ return values_{1}_{2}[_state.PeekNextAlternative()]; }}", fieldType, t.Ident, c.Ident).AppendLine();
    186         }
    187       }
    188     }
    189     private string GenerateConstructorSource(GPDefNode ast) {
    190       var sb = new SourceBuilder();
    191       // generate code to initialize the tables for terminals
    192       foreach (var t in ast.Terminals.OfType<TerminalNode>()) {
    193         if (t.Constraints.Any()) {
    194           foreach (var constraint in t.Constraints) {
    195             sb.AppendFormat("values_{0}_{1} = GetAllowed{0}_{1}().ToArray();", t.Ident, constraint.Ident);
    196           }
    197           sb.AppendFormat("cardinalities[\"{0}\"] = new Dictionary<string, int>() {{ ", t.Ident);
    198           foreach (var constraint in t.Constraints) {
    199             sb.AppendFormat("{{ \"{1}\", values_{0}_{1}.Length }}, ", t.Ident, constraint.Ident);
    200           }
    201           sb.Append("};").AppendLine();
    202         }
    203       }
    204       return sb.ToString();
    205     }
    206 
    207 
     187        }
     188      }
     189    }
    208190    #endregion
    209191
    210192    private string GenerateInterpreterSource(AttributedGrammar grammar) {
    211193      var sb = new SourceBuilder();
     194      GenerateInterpreterStart(grammar, sb);
    212195
    213196      // generate methods for all nonterminals and terminals using the grammar instance
     
    221204    }
    222205
     206    private void GenerateInterpreterStart(AttributedGrammar grammar, SourceBuilder sb) {
     207      var s = grammar.StartSymbol;
     208      // create the method which can be called from the fitness function
     209      if (!s.Attributes.Any())
     210        sb.AppendFormat("private void {0}() {{", s.Name).BeginBlock();
     211      else
     212        sb.AppendFormat("private void {0}({1}) {{", s.Name, s.GetAttributeString()).BeginBlock();
     213
     214      // get formal parameters of start symbol
     215      var attr = s.Attributes;
     216
     217      // actual parameter are the same as formalparameter only without type identifier
     218      string actualParameter;
     219      if (attr.Any())
     220        actualParameter = attr.Skip(1).Aggregate(attr.First().AttributeType + " " + attr.First().Name, (str, a) => str + ", " + a.AttributeType + " " + a.Name);
     221      else
     222        actualParameter = string.Empty;
     223      sb.AppendLine("_state.Reset();");
     224      sb.AppendFormat("{0}(_state, {1});", s.Name, actualParameter).AppendLine();
     225      sb.AppendLine("}").EndBlock();
     226    }
     227
    223228    private void GenerateInterpreterMethod(AttributedGrammar g, ISymbol s, SourceBuilder sb) {
    224       // if this is the start symbol we additionally have to create the method which can be called from the fitness function
    225       if (g.StartSymbol.Equals(s)) {
    226         if (!s.Attributes.Any())
    227           sb.AppendFormat("private void {0}() {{", s.Name).BeginBlock();
    228         else
    229           sb.AppendFormat("private void {0}({1}) {{", s.Name, s.GetAttributeString()).BeginBlock();
    230 
    231         // get formal parameters of start symbol
    232         var attr = g.StartSymbol.Attributes;
    233 
    234         // actual parameter are the same as formalparameter only without type identifier
    235         string actualParameter;
    236         if (attr.Any())
    237           actualParameter = attr.Skip(1).Aggregate(attr.First().AttributeType + " " + attr.First().Name, (str, a) => str + ", " + a.AttributeType + " " + a.Name);
    238         else
    239           actualParameter = string.Empty;
    240         sb.AppendLine("_state.Reset();");
    241         sb.AppendFormat("{0}(_state, {1});", g.StartSymbol.Name, actualParameter).AppendLine();
    242         sb.AppendLine("}").EndBlock();
    243       }
    244 
    245229      if (!s.Attributes.Any())
    246230        sb.AppendFormat("private void {0}(ISolverState _state) {{", s.Name).BeginBlock();
     
    272256        sb.AppendFormat("case {0}: {{ ", i).BeginBlock();
    273257
    274         // this only works for alternatives with a single non-terminal symbol (ignoring semantic symbols) so far!
     258        // this only works for alternatives with a single non-terminal symbol (ignoring semantic symbols)!
    275259        // a way to handle this is through grammar transformation (the examplary grammars all have the correct from)
    276260        Debug.Assert(alt.Count(symb => !(symb is SemanticSymbol)) == 1);
     
    295279    }
    296280
    297     private string GenerateTerminalInterpreterMethod(ISymbol s, SourceBuilder sb) {
     281    private void GenerateTerminalInterpreterMethod(ISymbol s, SourceBuilder sb) {
    298282      // if the terminal symbol has attributes then we must samples values for these attributes
    299283      if (!s.Attributes.Any())
     
    310294      }
    311295      sb.Append("}").EndBlock();
    312       return sb.ToString();
    313296    }
    314297  }
Note: See TracChangeset for help on using the changeset viewer.