Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
03/18/19 17:24:30 (6 years ago)
Author:
abeham
Message:

#2521: merged trunk changes up to r15681 into branch (removal of trunk/sources)

Location:
branches/2521_ProblemRefactoring
Files:
8 edited
1 copied

Legend:

Unmodified
Added
Removed
  • branches/2521_ProblemRefactoring

  • branches/2521_ProblemRefactoring/HeuristicLab.Problems.DataAnalysis.Symbolic

  • branches/2521_ProblemRefactoring/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Formatters/SymbolicDataAnalysisExpressionCSharpFormatter.cs

    r13116 r16692  
    11#region License Information
    22/* HeuristicLab
    3  * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
     3 * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
    44 *
    55 * This file is part of HeuristicLab.
     
    2525using System.Linq;
    2626using System.Text;
     27using System.Text.RegularExpressions;
    2728using HeuristicLab.Common;
    2829using HeuristicLab.Core;
     
    5354      GenerateFooter(strBuilder);
    5455      return strBuilder.ToString();
     56    }
     57
     58    private string VariableName2Identifier(string name) {     
     59      /*
     60       * identifier-start-character:
     61       *    letter-character
     62       *    _ (the underscore character U+005F)
     63       *  identifier-part-characters:
     64       *    identifier-part-character
     65       *    identifier-part-characters   identifier-part-character
     66       *  identifier-part-character:
     67       *    letter-character
     68       *    decimal-digit-character
     69       *    connecting-character
     70       *    combining-character
     71       *    formatting-character
     72       *  letter-character:
     73       *    A Unicode character of classes Lu, Ll, Lt, Lm, Lo, or Nl
     74       *    A unicode-escape-sequence representing a character of classes Lu, Ll, Lt, Lm, Lo, or Nl
     75       *  combining-character:
     76       *    A Unicode character of classes Mn or Mc
     77       *    A unicode-escape-sequence representing a character of classes Mn or Mc
     78       *  decimal-digit-character:
     79       *    A Unicode character of the class Nd
     80       *    A unicode-escape-sequence representing a character of the class Nd
     81       *  connecting-character:
     82       *    A Unicode character of the class Pc
     83       *    A unicode-escape-sequence representing a character of the class Pc
     84       *  formatting-character:
     85       *    A Unicode character of the class Cf
     86       *    A unicode-escape-sequence representing a character of the class Cf
     87       */
     88
     89      var invalidIdentifierStarts = new Regex(@"[^_\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}]");
     90      var invalidIdentifierParts = new Regex(@"[^\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\p{Cf}]");
     91      return "@" +
     92        (invalidIdentifierStarts.IsMatch(name.Substring(0, 1)) ? "_" : "") + // prepend '_' if necessary
     93        invalidIdentifierParts.Replace(name, "_");
    5594    }
    5695
     
    106145        if (node is VariableTreeNode) {
    107146          var varNode = node as VariableTreeNode;
    108           strBuilder.AppendFormat("{0} * {1}", varNode.VariableName, varNode.Weight.ToString("g17", CultureInfo.InvariantCulture));
     147          strBuilder.AppendFormat("{0} * {1}", VariableName2Identifier(varNode.VariableName), varNode.Weight.ToString("g17", CultureInfo.InvariantCulture));
    109148        } else if (node is ConstantTreeNode) {
    110149          var constNode = node as ConstantTreeNode;
    111150          strBuilder.Append(constNode.Value.ToString("g17", CultureInfo.InvariantCulture));
     151        } else if (node.Symbol is FactorVariable) {
     152          var factorNode = node as FactorVariableTreeNode;
     153          FormatFactor(factorNode, strBuilder);
     154        } else if (node.Symbol is BinaryFactorVariable) {
     155          var binFactorNode = node as BinaryFactorVariableTreeNode;
     156          FormatBinaryFactor(binFactorNode, strBuilder);
    112157        } else {
    113158          throw new NotSupportedException("Formatting of symbol: " + node.Symbol + " not supported for C# symbolic expression tree formatter.");
    114159        }
    115160      }
     161    }
     162
     163    private void FormatFactor(FactorVariableTreeNode node, StringBuilder strBuilder) {
     164      strBuilder.AppendFormat("EvaluateFactor({0}, new [] {{ {1} }}, new [] {{ {2} }})", VariableName2Identifier(node.VariableName),
     165        string.Join(",", node.Symbol.GetVariableValues(node.VariableName).Select(name => "\"" + name + "\"")), string.Join(",", node.Weights.Select(v => v.ToString(CultureInfo.InvariantCulture))));
     166    }
     167
     168    private void FormatBinaryFactor(BinaryFactorVariableTreeNode node, StringBuilder strBuilder) {
     169      strBuilder.AppendFormat(CultureInfo.InvariantCulture, "EvaluateBinaryFactor({0}, \"{1}\", {2})", VariableName2Identifier(node.VariableName), node.VariableValue, node.Weight);
    116170    }
    117171
     
    182236      GenerateAverageSource(strBuilder);
    183237      GenerateIfThenElseSource(strBuilder);
     238      GenerateFactorSource(strBuilder);
     239      GenerateBinaryFactorSource(strBuilder);
    184240      strBuilder.Append(Environment.NewLine + "public static double Evaluate (");
    185241
    186       HashSet<string> varNames = new HashSet<string>();
    187       foreach (var node in symbolicExpressionTree.IterateNodesPostfix().Where(x => x is VariableTreeNode)) {
    188         varNames.Add(((VariableTreeNode)node).VariableName);
    189       }
    190 
    191       var orderedNames = varNames.OrderBy(n => n, new NaturalStringComparer()).Select(n => "double " + n);
     242      // here we don't have access to problemData to determine the type for each variable (double/string) therefore we must distinguish based on the symbol type
     243      HashSet<string> doubleVarNames = new HashSet<string>();
     244      foreach (var node in symbolicExpressionTree.IterateNodesPostfix().Where(x => x is VariableTreeNode || x is VariableConditionTreeNode)) {
     245        doubleVarNames.Add(((IVariableTreeNode)node).VariableName);
     246      }
     247
     248      HashSet<string> stringVarNames = new HashSet<string>();
     249      foreach (var node in symbolicExpressionTree.IterateNodesPostfix().Where(x => x is BinaryFactorVariableTreeNode || x is FactorVariableTreeNode)) {
     250        stringVarNames.Add(((IVariableTreeNode)node).VariableName);
     251      }
     252
     253      var orderedNames = stringVarNames.OrderBy(n => n, new NaturalStringComparer()).Select(n => "string " + VariableName2Identifier(n) + " /* " + n + " */");
    192254      strBuilder.Append(string.Join(", ", orderedNames));
     255
     256      if (stringVarNames.Any() && doubleVarNames.Any())
     257        strBuilder.AppendLine(",");
     258      orderedNames = doubleVarNames.OrderBy(n => n, new NaturalStringComparer()).Select(n => "double " + VariableName2Identifier(n) + " /* " + n + " */");
     259      strBuilder.Append(string.Join(", ", orderedNames));
     260
    193261
    194262      strBuilder.AppendLine(") {");
     
    198266    private void GenerateFooter(StringBuilder strBuilder) {
    199267      strBuilder.AppendLine(";");
     268
    200269      strBuilder.AppendLine("return result;");
    201270      strBuilder.AppendLine("}");
     
    215284      strBuilder.AppendLine("}");
    216285    }
     286
     287    private void GenerateFactorSource(StringBuilder strBuilder) {
     288      strBuilder.AppendLine("private static double EvaluateFactor(string factorValue, string[] factorValues, double[] constants) {");
     289      strBuilder.AppendLine("   for(int i=0;i<factorValues.Length;i++) " +
     290                            "      if(factorValues[i] == factorValue) return constants[i];" +
     291                            "   throw new ArgumentException();");
     292      strBuilder.AppendLine("}");
     293    }
     294
     295    private void GenerateBinaryFactorSource(StringBuilder strBuilder) {
     296      strBuilder.AppendLine("private static double EvaluateBinaryFactor(string factorValue, string targetValue, double weight) {");
     297      strBuilder.AppendLine("  return factorValue == targetValue ? weight : 0.0;");
     298      strBuilder.AppendLine("}");
     299    }
     300
    217301  }
    218302}
  • branches/2521_ProblemRefactoring/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Formatters/SymbolicDataAnalysisExpressionExcelFormatter.cs

    r12509 r16692  
    11#region License Information
    22/* HeuristicLab
    3  * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
     3 * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
    44 *
    55 * This file is part of HeuristicLab.
     
    5151      while (dividend > 0) {
    5252        int modulo = (dividend - 1) % 26;
    53         columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
     53        columnName = System.Convert.ToChar(65 + modulo) + columnName;
    5454        dividend = (int)((dividend - modulo) / 26);
    5555      }
     
    6060    private readonly Dictionary<string, string> variableNameMapping = new Dictionary<string, string>();
    6161    private int currentVariableIndex = 0;
    62     private string GetColumnToVariableName(string variabelName) {
    63       if (!variableNameMapping.ContainsKey(variabelName)) {
     62    private string GetColumnToVariableName(string varName) {
     63      if (!variableNameMapping.ContainsKey(varName)) {
    6464        currentVariableIndex++;
    65         variableNameMapping.Add(variabelName, GetExcelColumnName(currentVariableIndex));
    66       }
    67       return string.Format("${0}1", variableNameMapping[variabelName]);
     65        variableNameMapping.Add(varName, GetExcelColumnName(currentVariableIndex));
     66      }
     67      return string.Format("${0}1", variableNameMapping[varName]);
    6868    }
    6969    public string Format(ISymbolicExpressionTree symbolicExpressionTree) {
     
    7171    }
    7272
     73
    7374    public string Format(ISymbolicExpressionTree symbolicExpressionTree, IDataset dataset) {
     75      if (dataset != null)
     76        return FormatWithMapping(symbolicExpressionTree, CalculateVariableMapping(symbolicExpressionTree, dataset));
     77      else return FormatWithMapping(symbolicExpressionTree, new Dictionary<string, string>());
     78    }
     79
     80    public string FormatWithMapping(ISymbolicExpressionTree symbolicExpressionTree, Dictionary<string, string> variableNameMapping) {
     81      foreach (var kvp in variableNameMapping) this.variableNameMapping.Add(kvp.Key, kvp.Value);
    7482      var stringBuilder = new StringBuilder();
    75       if (dataset != null) CalculateVariableMapping(symbolicExpressionTree, dataset);
    7683
    7784      stringBuilder.Append("=");
    7885      stringBuilder.Append(FormatRecursively(symbolicExpressionTree.Root));
    7986
    80       foreach (var variable in variableNameMapping) {
     87      foreach (var variable in this.variableNameMapping) {
    8188        stringBuilder.AppendLine();
    8289        stringBuilder.Append(variable.Key + " = " + variable.Value);
     
    8592    }
    8693
    87     private void CalculateVariableMapping(ISymbolicExpressionTree tree, IDataset dataset) {
    88       int columnIndex = 0;
     94    private Dictionary<string, string> CalculateVariableMapping(ISymbolicExpressionTree tree, IDataset dataset) {
     95      var mapping = new Dictionary<string, string>();
    8996      int inputIndex = 0;
    90       var usedVariables = tree.IterateNodesPrefix().OfType<VariableTreeNode>().Select(v => v.VariableName).Distinct();
     97      var usedVariables = tree.IterateNodesPrefix().OfType<IVariableTreeNode>().Select(v => v.VariableName).Distinct().ToArray();
    9198      foreach (var variable in dataset.VariableNames) {
    92         columnIndex++;
    9399        if (!usedVariables.Contains(variable)) continue;
    94100        inputIndex++;
    95         variableNameMapping[variable] = GetExcelColumnName(inputIndex);
    96       }
     101        mapping[variable] = GetExcelColumnName(inputIndex);
     102      }
     103      return mapping;
    97104    }
    98105
     
    190197        stringBuilder.Append(variableTreeNode.Weight.ToString(CultureInfo.InvariantCulture));
    191198        stringBuilder.Append("*");
    192         stringBuilder.Append(GetColumnToVariableName(variableTreeNode.VariableName));// + LagToString(currentLag));
     199        stringBuilder.Append(GetColumnToVariableName(variableTreeNode.VariableName));
     200      } else if (symbol is BinaryFactorVariable) {
     201        var binFactorNode = node as BinaryFactorVariableTreeNode;
     202        stringBuilder.AppendFormat("IF({0}=\"{1}\", {2}, 0)",
     203          GetColumnToVariableName(binFactorNode.VariableName),
     204          binFactorNode.VariableValue,
     205          binFactorNode.Weight.ToString(CultureInfo.InvariantCulture)
     206          );
     207      } else if (symbol is FactorVariable) {
     208        var factorNode = node as FactorVariableTreeNode;
     209        var values = factorNode.Symbol.GetVariableValues(factorNode.VariableName).ToArray();
     210        var w = factorNode.Weights;
     211        // create nested if
     212        for (int i = 0; i < values.Length; i++) {
     213          stringBuilder.AppendFormat("IF({0}=\"{1}\", {2}, ",
     214            GetColumnToVariableName(factorNode.VariableName),
     215            values[i],
     216            w[i].ToString(CultureInfo.InvariantCulture));
     217        }
     218        stringBuilder.Append("\"\""); // return empty string on unknown value
     219        stringBuilder.Append(')', values.Length); // add closing parenthesis
    193220      } else if (symbol is Power) {
    194221        stringBuilder.Append("POWER(");
     
    213240      } else if (symbol is VariableCondition) {
    214241        VariableConditionTreeNode variableConditionTreeNode = node as VariableConditionTreeNode;
    215         double threshold = variableConditionTreeNode.Threshold;
    216         double slope = variableConditionTreeNode.Slope;
    217         string p = "(1 / (1 + EXP(-" + slope.ToString(CultureInfo.InvariantCulture) + " * (" + GetColumnToVariableName(variableConditionTreeNode.VariableName) + "-" + threshold.ToString(CultureInfo.InvariantCulture) + "))))";
    218         stringBuilder.Append("((");
    219         stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
    220         stringBuilder.Append("*");
    221         stringBuilder.Append(p);
    222         stringBuilder.Append(") + (");
    223         stringBuilder.Append(FormatRecursively(node.GetSubtree(1)));
    224         stringBuilder.Append("*(");
    225         stringBuilder.Append("1 - " + p + ")");
    226         stringBuilder.Append("))");
     242        if (!variableConditionTreeNode.Symbol.IgnoreSlope) {
     243          double threshold = variableConditionTreeNode.Threshold;
     244          double slope = variableConditionTreeNode.Slope;
     245          string p = "(1 / (1 + EXP(-" + slope.ToString(CultureInfo.InvariantCulture) + " * (" +
     246                     GetColumnToVariableName(variableConditionTreeNode.VariableName) + "-" +
     247                     threshold.ToString(CultureInfo.InvariantCulture) + "))))";
     248          stringBuilder.Append("((");
     249          stringBuilder.Append(FormatRecursively(node.GetSubtree(0)));
     250          stringBuilder.Append("*");
     251          stringBuilder.Append(p);
     252          stringBuilder.Append(") + (");
     253          stringBuilder.Append(FormatRecursively(node.GetSubtree(1)));
     254          stringBuilder.Append("*(");
     255          stringBuilder.Append("1 - " + p + ")");
     256          stringBuilder.Append("))");
     257        } else {
     258          stringBuilder.AppendFormat(CultureInfo.InvariantCulture, "(IF({0} <= {1}, {2}, {3}))",
     259            GetColumnToVariableName(variableConditionTreeNode.VariableName),
     260            variableConditionTreeNode.Threshold,
     261            FormatRecursively(node.GetSubtree(0)),
     262            FormatRecursively(node.GetSubtree(1))
     263            );
     264        }
    227265      } else if (symbol is Xor) {
    228266        stringBuilder.Append("IF(");
  • branches/2521_ProblemRefactoring/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Formatters/SymbolicDataAnalysisExpressionLatexFormatter.cs

    r12012 r16692  
    11#region License Information
    22/* HeuristicLab
    3  * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
     3 * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
    44 *
    55 * This file is part of HeuristicLab.
     
    3333  [StorableClass]
    3434  public sealed class SymbolicDataAnalysisExpressionLatexFormatter : NamedItem, ISymbolicExpressionTreeStringFormatter {
    35     private readonly List<double> constants;
     35    private readonly List<KeyValuePair<string, double>> constants;
     36    private int constIndex;
    3637    private int targetCount;
    3738    private int currentLag;
     39    private string targetVariable;
     40    private bool containsTimeSeriesSymbol;
    3841
    3942    [StorableConstructor]
     
    4144    private SymbolicDataAnalysisExpressionLatexFormatter(SymbolicDataAnalysisExpressionLatexFormatter original, Cloner cloner)
    4245      : base(original, cloner) {
    43       constants = new List<double>(original.constants);
     46      constants = new List<KeyValuePair<string, double>>(original.constants);
     47      constIndex = original.constIndex;
     48      currentLag = original.currentLag;
     49      targetCount = original.targetCount;
    4450    }
    4551    public SymbolicDataAnalysisExpressionLatexFormatter()
     
    4753      Name = ItemName;
    4854      Description = ItemDescription;
    49       constants = new List<double>();
     55      constants = new List<KeyValuePair<string, double>>();
    5056    }
    5157
     
    5561
    5662    public string Format(ISymbolicExpressionTree symbolicExpressionTree) {
     63      return Format(symbolicExpressionTree, null);
     64    }
     65    public string Format(ISymbolicExpressionTree symbolicExpressionTree, string targetVariable) {
    5766      try {
    5867        StringBuilder strBuilder = new StringBuilder();
    5968        constants.Clear();
     69        constIndex = 0;
     70        this.targetVariable = targetVariable;
     71        containsTimeSeriesSymbol = symbolicExpressionTree.IterateNodesBreadth().Any(n => IsTimeSeriesSymbol(n.Symbol));
    6072        strBuilder.AppendLine(FormatRecursively(symbolicExpressionTree.Root));
    6173        return strBuilder.ToString();
    62       }
    63       catch (NotImplementedException ex) {
     74      } catch (NotImplementedException ex) {
    6475        return ex.Message + Environment.NewLine + ex.StackTrace;
    6576      }
     77    }
     78    static bool IsTimeSeriesSymbol(ISymbol s) {
     79      return s is TimeLag || s is Integral || s is Derivative || s is LaggedVariable;
    6680    }
    6781
     
    7589      }
    7690      int i = 1;
    77       foreach (SymbolicExpressionTreeNode subTree in node.Subtrees.Skip(1)) {
     91      foreach (var subTree in node.Subtrees.Skip(1)) {
    7892        FormatSep(node, strBuilder, i);
    7993        // format the whole subtree
     
    99113      } else if (node.Symbol is Division) {
    100114        if (node.SubtreeCount == 1) {
    101           strBuilder.Append(@" \cfrac{1");
     115          strBuilder.Append(@" \cfrac{1}{");
    102116        } else {
    103117          strBuilder.Append(@" \cfrac{ ");
     
    166180        strBuilder.Append(@" \operatorname{if}  \left( ");
    167181      } else if (node.Symbol is Constant) {
    168         strBuilder.Append("c_{" + constants.Count + "} ");
     182        var constName = "c_{" + constIndex + "}";
     183        constIndex++;
    169184        var constNode = node as ConstantTreeNode;
    170         constants.Add(constNode.Value);
     185        if (constNode.Value.IsAlmost(1.0)) {
     186          strBuilder.Append("1 ");
     187        } else {
     188          strBuilder.Append(constName);
     189          constants.Add(new KeyValuePair<string, double>(constName, constNode.Value));
     190        }
     191
     192      } else if (node.Symbol is FactorVariable) {
     193        var factorNode = node as FactorVariableTreeNode;
     194        var constName = "c_{" + constIndex + "}";
     195        strBuilder.Append(constName + " ");
     196        foreach (var e in factorNode.Symbol.GetVariableValues(factorNode.VariableName)
     197          .Zip(factorNode.Weights, Tuple.Create)) {
     198          constants.Add(new KeyValuePair<string, double>("c_{" + constIndex + ", " + EscapeLatexString(factorNode.VariableName) + "=" + EscapeLatexString(e.Item1) + "}", e.Item2));
     199        }
     200        constIndex++;
     201      } else if (node.Symbol is BinaryFactorVariable) {
     202        var binFactorNode = node as BinaryFactorVariableTreeNode;
     203        if (!binFactorNode.Weight.IsAlmost((1.0))) {
     204          var constName = "c_{" + constIndex + "}";
     205          strBuilder.Append(constName + "  \\cdot");
     206          constants.Add(new KeyValuePair<string, double>(constName, binFactorNode.Weight));
     207          constIndex++;
     208        }
     209        strBuilder.Append("(" + EscapeLatexString(binFactorNode.VariableName));
     210        strBuilder.Append(LagToString(currentLag));
     211        strBuilder.Append(" = " + EscapeLatexString(binFactorNode.VariableValue) + " )");
    171212      } else if (node.Symbol is LaggedVariable) {
    172213        var laggedVarNode = node as LaggedVariableTreeNode;
    173214        if (!laggedVarNode.Weight.IsAlmost(1.0)) {
    174           strBuilder.Append("c_{" + constants.Count + "} \\cdot ");
    175           constants.Add(laggedVarNode.Weight);
     215          var constName = "c_{" + constIndex + "}";
     216          strBuilder.Append(constName + "  \\cdot");
     217          constants.Add(new KeyValuePair<string, double>(constName, laggedVarNode.Weight));
     218          constIndex++;
    176219        }
    177220        strBuilder.Append(EscapeLatexString(laggedVarNode.VariableName));
     
    181224        var varNode = node as VariableTreeNode;
    182225        if (!varNode.Weight.IsAlmost((1.0))) {
    183           strBuilder.Append("c_{" + constants.Count + "} \\cdot ");
    184           constants.Add(varNode.Weight);
     226          var constName = "c_{" + constIndex + "}";
     227          strBuilder.Append(constName + "  \\cdot");
     228          constants.Add(new KeyValuePair<string, double>(constName, varNode.Weight));
     229          constIndex++;
    185230        }
    186231        strBuilder.Append(EscapeLatexString(varNode.VariableName));
     
    197242        strBuilder.Append(invokeNode.Symbol.FunctionName + @" \left( ");
    198243      } else if (node.Symbol is StartSymbol) {
    199         strBuilder.Append("target_" + (targetCount++) + "(t) & = ");
     244        FormatStartSymbol(strBuilder);
    200245      } else if (node.Symbol is Argument) {
    201246        var argSym = node.Symbol as Argument;
     
    216261      } else if (node.Symbol is VariableCondition) {
    217262        var conditionTreeNode = node as VariableConditionTreeNode;
    218         string p = @"1 /  1 + \exp  - c_{" + constants.Count + "} ";
    219         constants.Add(conditionTreeNode.Slope);
    220         p += @" \cdot " + EscapeLatexString(conditionTreeNode.VariableName) + LagToString(currentLag) + " - c_{" + constants.Count + @"}   ";
    221         constants.Add(conditionTreeNode.Threshold);
     263        var constName = "c_{" + constants.Count + "}";
     264        string p = @"1 /  1 + \exp  - " + constName + " ";
     265        constants.Add(new KeyValuePair<string, double>(constName, conditionTreeNode.Slope));
     266        constIndex++;
     267        var const2Name = "c_{" + constants.Count + @"}";
     268        p += @" \cdot " + EscapeLatexString(conditionTreeNode.VariableName) + LagToString(currentLag) + " - " + const2Name + "   ";
     269        constants.Add(new KeyValuePair<string, double>(const2Name, conditionTreeNode.Threshold));
     270        constIndex++;
    222271        strBuilder.Append(@" \left( " + p + @"\cdot ");
    223272      } else {
     
    303352      } else if (node.Symbol is StartSymbol) {
    304353        strBuilder.Append(@"\\" + Environment.NewLine);
    305         strBuilder.Append("target_" + (targetCount++) + "(t) & = ");
     354        FormatStartSymbol(strBuilder);
    306355      } else if (node.Symbol is Power) {
    307356        strBuilder.Append(@"\right) ^ { \operatorname{round} \left(");
     
    310359      } else if (node.Symbol is VariableCondition) {
    311360        var conditionTreeNode = node as VariableConditionTreeNode;
    312         string p = @"1 / \left( 1 + \exp \left( - c_{" + constants.Count + "} ";
    313         constants.Add(conditionTreeNode.Slope);
    314         p += @" \cdot " + EscapeLatexString(conditionTreeNode.VariableName) + LagToString(currentLag) + " - c_{" + constants.Count + @"} \right) \right) \right)   ";
    315         constants.Add(conditionTreeNode.Threshold);
     361        var const1Name = "c_{" + constants.Count + "}";
     362        string p = @"1 / \left( 1 + \exp \left( - " + const1Name + " ";
     363        constants.Add(new KeyValuePair<string, double>(const1Name, conditionTreeNode.Slope));
     364        constIndex++;
     365        var const2Name = "c_{" + constants.Count + "}";
     366        p += @" \cdot " + EscapeLatexString(conditionTreeNode.VariableName) + LagToString(currentLag) + " - " + const2Name + " \right) \right) \right)   ";
     367        constants.Add(new KeyValuePair<string, double>(const2Name, conditionTreeNode.Threshold));
     368        constIndex++;
    316369        strBuilder.Append(@" +  \left( 1 - " + p + @" \right) \cdot ");
    317370      } else {
     
    391444      } else if (node.Symbol is LaggedVariable) {
    392445      } else if (node.Symbol is Variable) {
     446      } else if (node.Symbol is FactorVariable) {
     447      } else if (node.Symbol is BinaryFactorVariable) {
    393448      } else if (node.Symbol is ProgramRootSymbol) {
    394449        strBuilder
     
    398453        // output all constant values
    399454        if (constants.Count > 0) {
    400           int i = 0;
    401455          foreach (var constant in constants) {
    402456            // replace "." with ".&" to align decimal points
    403             var constStr = string.Format(System.Globalization.NumberFormatInfo.InvariantInfo, "{0:G5}", constant);
     457            var constStr = string.Format(System.Globalization.NumberFormatInfo.InvariantInfo, "{0:G5}", constant.Value);
    404458            if (!constStr.Contains(".")) constStr = constStr + ".0";
    405             constStr = constStr.Replace(".", "\\negthickspace&.");  // fix problem in rendering of aligned expressions
    406             strBuilder.Append("c_{" + i + "}& = & " + constStr);
     459            constStr = constStr.Replace(".", "&.");  // fix problem in rendering of aligned expressions
     460            strBuilder.Append(constant.Key + "& = & " + constStr);
    407461            strBuilder.Append(@"\\");
    408             i++;
    409462          }
    410463        }
     
    433486    }
    434487
     488    private void FormatStartSymbol(StringBuilder strBuilder) {
     489      strBuilder.Append(targetVariable ?? "target_" + (targetCount++));
     490      if (containsTimeSeriesSymbol)
     491        strBuilder.Append("(t)");
     492      strBuilder.Append(" & = ");
     493    }
     494
    435495    private string LagToString(int lag) {
    436496      if (lag < 0) {
  • branches/2521_ProblemRefactoring/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Formatters/SymbolicDataAnalysisExpressionMATLABFormatter.cs

    r12012 r16692  
    11#region License Information
    22/* HeuristicLab
    3  * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
     3 * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
    44 *
    55 * This file is part of HeuristicLab.
     
    2121
    2222using System.Globalization;
     23using System.Linq;
    2324using System.Text;
    2425using HeuristicLab.Common;
     
    7778      stringBuilder.AppendLine("  y = (f0 + 2*f1 - 2*f3 - f4) / 8;");
    7879      stringBuilder.AppendLine("end");
     80
     81      var factorVariableNames =
     82        symbolicExpressionTree.IterateNodesPostfix()
     83          .OfType<FactorVariableTreeNode>()
     84          .Select(n => n.VariableName)
     85          .Distinct();
     86
     87      foreach (var factorVarName in factorVariableNames) {
     88        var factorSymb = symbolicExpressionTree.IterateNodesPostfix()
     89          .OfType<FactorVariableTreeNode>()
     90          .First(n => n.VariableName == factorVarName)
     91          .Symbol;
     92        stringBuilder.AppendFormat("function y = switch_{0}(val, v)", factorVarName).AppendLine();
     93        var values = factorSymb.GetVariableValues(factorVarName).ToArray();
     94        stringBuilder.AppendLine("switch val");
     95        for (int i = 0; i < values.Length; i++) {
     96          stringBuilder.AppendFormat(CultureInfo.InvariantCulture, "  case \"{0}\" y = v({1})", values[i], i).AppendLine();
     97        }
     98        stringBuilder.AppendLine("end");
     99        stringBuilder.AppendLine();
     100      }
     101
    79102      return stringBuilder.ToString();
    80103    }
     
    296319        stringBuilder.Append("*");
    297320        stringBuilder.Append(variableTreeNode.VariableName + LagToString(currentLag));
     321      } else if (symbol is HeuristicLab.Problems.DataAnalysis.Symbolic.FactorVariable) {
     322        var factorNode = node as FactorVariableTreeNode;
     323        var weights = string.Join(" ", factorNode.Weights.Select(w => w.ToString("G17", CultureInfo.InvariantCulture)));
     324        stringBuilder.AppendFormat("switch_{0}(\"{1}\",[{2}])",
     325          factorNode.VariableName, factorNode.VariableName, weights)
     326          .AppendLine();
     327      } else if (symbol is HeuristicLab.Problems.DataAnalysis.Symbolic.BinaryFactorVariable) {
     328        var factorNode = node as BinaryFactorVariableTreeNode;
     329        stringBuilder.AppendFormat(CultureInfo.InvariantCulture,
     330          "((strcmp({0},\"{1}\")==1) * {2:G17})", factorNode.VariableName, factorNode.VariableValue, factorNode.Weight);
    298331      } else if (symbol is Power) {
    299332        stringBuilder.Append("(");
  • branches/2521_ProblemRefactoring/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Formatters/SymbolicDataAnalysisExpressionMathematicaFormatter.cs

    r12982 r16692  
    11#region License Information
    22/* HeuristicLab
    3  * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
     3 * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
    44 *
    55 * This file is part of HeuristicLab.
     
    110110        }
    111111      } else {
    112         if (node is VariableTreeNode) {
     112        // terminals
     113        if (node.Symbol is Variable) {
    113114          var varNode = node as VariableTreeNode;
    114115          strBuilder.AppendFormat("Times[{0}, {1}]", varNode.VariableName, varNode.Weight.ToString("G17", CultureInfo.InvariantCulture));
    115         } else if (node is ConstantTreeNode) {
     116        } else if (node.Symbol is Constant) {
    116117          var constNode = node as ConstantTreeNode;
    117118          strBuilder.Append(constNode.Value.ToString("G17", CultureInfo.InvariantCulture));
     119        } else if (node.Symbol is FactorVariable) {
     120          var factorNode = node as FactorVariableTreeNode;
     121          strBuilder.AppendFormat("Switch[{0},", factorNode.VariableName);
     122          var varValues = factorNode.Symbol.GetVariableValues(factorNode.VariableName).ToArray();
     123          var weights = varValues.Select(factorNode.GetValue).ToArray();
     124
     125          var weightStr = string.Join(", ",
     126            varValues.Zip(weights, (s, d) => string.Format(CultureInfo.InvariantCulture, "\"{0}\", {1:G17}", s, d)));
     127          strBuilder.Append(weightStr);
     128          strBuilder.Append("]");
     129        } else if (node.Symbol is BinaryFactorVariable) {
     130          var factorNode = node as BinaryFactorVariableTreeNode;
     131          strBuilder.AppendFormat(CultureInfo.InvariantCulture, "If[{0}==\"{1}\",{2:G17},0.0]",
     132            factorNode.VariableName, factorNode.VariableValue, factorNode.Weight);
    118133        } else {
    119134          throw new NotSupportedException("Formatting of symbol: " + node.Symbol + " is not supported.");
  • branches/2521_ProblemRefactoring/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Formatters/SymbolicDataAnalysisExpressionSmalltalkFormatter.cs

    r12012 r16692  
    11#region License Information
    22/* HeuristicLab
    3  * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
     3 * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
    44 *
    55 * This file is part of HeuristicLab.
     
    115115        stringBuilder.Append("]");
    116116      } else if (symbol is LaggedVariable) {
    117         stringBuilder.Append("lagged variable not implemented");
     117        stringBuilder.Append("lagged variables are not supported");
    118118      } else if (symbol is LessThan) {
    119119        stringBuilder.Append("(");
     
    165165        stringBuilder.Append("*");
    166166        stringBuilder.Append(variableTreeNode.VariableName);
     167      } else if (symbol is BinaryFactorVariable || symbol is FactorVariable) {
     168        stringBuilder.Append("factor variables are not supported");
    167169      } else {
    168170        stringBuilder.Append("(");
Note: See TracChangeset for help on using the changeset viewer.