Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
04/04/17 17:52:44 (8 years ago)
Author:
gkronber
Message:

#2650: merged the factors branch into trunk

Location:
trunk/sources
Files:
9 edited

Legend:

Unmodified
Added
Removed
  • trunk/sources

  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic

  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Formatters/InfixExpressionFormatter.cs

    r14350 r14826  
    141141            strBuilder.Append(")");
    142142          }
     143        } else if (node.Symbol is FactorVariable) {
     144          var factorNode = node as FactorVariableTreeNode;
     145          if (factorNode.VariableName.Contains("'")) {
     146            strBuilder.AppendFormat("\"{0}\"", factorNode.VariableName);
     147          } else {
     148            strBuilder.AppendFormat("'{0}'", factorNode.VariableName);
     149          }
     150          strBuilder.AppendFormat("[{0}]",
     151            string.Join(", ", factorNode.Weights.Select(w => w.ToString(CultureInfo.InvariantCulture))));
     152        } else if (node.Symbol is BinaryFactorVariable) {
     153          var factorNode = node as BinaryFactorVariableTreeNode;
     154          if (!factorNode.Weight.IsAlmost(1.0)) {
     155            strBuilder.Append("(");
     156            strBuilder.AppendFormat(CultureInfo.InvariantCulture, "{0}", factorNode.Weight);
     157            strBuilder.Append("*");
     158          }
     159          if (factorNode.VariableName.Contains("'")) {
     160            strBuilder.AppendFormat("\"{0}\"", factorNode.VariableName);
     161          } else {
     162            strBuilder.AppendFormat("'{0}'", factorNode.VariableName);
     163          }
     164          strBuilder.Append(" = ");
     165          if (factorNode.VariableValue.Contains("'")) {
     166            strBuilder.AppendFormat("\"{0}\"", factorNode.VariableValue);
     167          } else {
     168            strBuilder.AppendFormat("'{0}'", factorNode.VariableValue);
     169          }
     170
     171          if (!factorNode.Weight.IsAlmost(1.0)) {
     172            strBuilder.Append(")");
     173          }
     174
    143175        } else if (node.Symbol is Constant) {
    144176          var constNode = node as ConstantTreeNode;
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Formatters/SymbolicDataAnalysisExpressionCSharpFormatter.cs

    r14185 r14826  
    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}
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Formatters/SymbolicDataAnalysisExpressionExcelFormatter.cs

    r14400 r14826  
    5151      while (dividend > 0) {
    5252        int modulo = (dividend - 1) % 26;
    53         columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
     53        columnName = 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    {
     82      foreach(var kvp in variableNameMapping) this.variableNameMapping.Add(kvp.Key,kvp.Value);
    7483      var stringBuilder = new StringBuilder();
    75       if (dataset != null) CalculateVariableMapping(symbolicExpressionTree, dataset);
    76 
     84     
    7785      stringBuilder.Append("=");
    7886      stringBuilder.Append(FormatRecursively(symbolicExpressionTree.Root));
    7987
    80       foreach (var variable in variableNameMapping) {
     88      foreach (var variable in this.variableNameMapping) {
    8189        stringBuilder.AppendLine();
    8290        stringBuilder.Append(variable.Key + " = " + variable.Value);
     
    8593    }
    8694
    87     private void CalculateVariableMapping(ISymbolicExpressionTree tree, IDataset dataset) {
    88       int columnIndex = 0;
     95    private Dictionary<string,string> CalculateVariableMapping(ISymbolicExpressionTree tree, IDataset dataset) {
     96      var mapping = new Dictionary<string,string>();
    8997      int inputIndex = 0;
    90       var usedVariables = tree.IterateNodesPrefix().OfType<VariableTreeNode>().Select(v => v.VariableName).Distinct();
     98      var usedVariables = tree.IterateNodesPrefix().OfType<IVariableTreeNode>().Select(v => v.VariableName).Distinct().ToArray();
    9199      foreach (var variable in dataset.VariableNames) {
    92         columnIndex++;
    93100        if (!usedVariables.Contains(variable)) continue;
    94101        inputIndex++;
    95         variableNameMapping[variable] = GetExcelColumnName(inputIndex);
    96       }
     102        mapping[variable] = GetExcelColumnName(inputIndex);
     103      }
     104      return mapping;
    97105    }
    98106
     
    190198        stringBuilder.Append(variableTreeNode.Weight.ToString(CultureInfo.InvariantCulture));
    191199        stringBuilder.Append("*");
    192         stringBuilder.Append(GetColumnToVariableName(variableTreeNode.VariableName));// + LagToString(currentLag));
     200        stringBuilder.Append(GetColumnToVariableName(variableTreeNode.VariableName));
     201      } else if (symbol is BinaryFactorVariable) {
     202        var binFactorNode = node as BinaryFactorVariableTreeNode;
     203        stringBuilder.AppendFormat("IF({0}=\"{1}\", {2}, 0)",
     204          GetColumnToVariableName(binFactorNode.VariableName),
     205          binFactorNode.VariableValue,
     206          binFactorNode.Weight.ToString(CultureInfo.InvariantCulture)
     207          );
     208      } else if (symbol is FactorVariable) {
     209        var factorNode = node as FactorVariableTreeNode;
     210        var values = factorNode.Symbol.GetVariableValues(factorNode.VariableName).ToArray();
     211        var w = factorNode.Weights;
     212        // create nested if
     213        for (int i = 0; i < values.Length; i++) {
     214          stringBuilder.AppendFormat("IF({0}=\"{1}\", {2}, ",
     215            GetColumnToVariableName(factorNode.VariableName),
     216            values[i],
     217            w[i].ToString(CultureInfo.InvariantCulture));
     218        }
     219        stringBuilder.Append("\"\""); // return empty string on unknown value
     220        stringBuilder.Append(')', values.Length); // add closing parenthesis
    193221      } else if (symbol is Power) {
    194222        stringBuilder.Append("POWER(");
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Formatters/SymbolicDataAnalysisExpressionLatexFormatter.cs

    r14367 r14826  
    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;
     
    4344    private SymbolicDataAnalysisExpressionLatexFormatter(SymbolicDataAnalysisExpressionLatexFormatter original, Cloner cloner)
    4445      : base(original, cloner) {
    45       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;
    4650    }
    4751    public SymbolicDataAnalysisExpressionLatexFormatter()
     
    4953      Name = ItemName;
    5054      Description = ItemDescription;
    51       constants = new List<double>();
     55      constants = new List<KeyValuePair<string, double>>();
    5256    }
    5357
     
    6367        StringBuilder strBuilder = new StringBuilder();
    6468        constants.Clear();
     69        constIndex = 0;
    6570        this.targetVariable = targetVariable;
    6671        containsTimeSeriesSymbol = symbolicExpressionTree.IterateNodesBreadth().Any(n => IsTimeSeriesSymbol(n.Symbol));
     
    8489      }
    8590      int i = 1;
    86       foreach (SymbolicExpressionTreeNode subTree in node.Subtrees.Skip(1)) {
     91      foreach (var subTree in node.Subtrees.Skip(1)) {
    8792        FormatSep(node, strBuilder, i);
    8893        // format the whole subtree
     
    175180        strBuilder.Append(@" \operatorname{if}  \left( ");
    176181      } else if (node.Symbol is Constant) {
     182        var constName = "c_{" + constIndex + "}";
     183        constIndex++;
    177184        var constNode = node as ConstantTreeNode;
    178185        if (constNode.Value.IsAlmost(1.0)) {
    179186          strBuilder.Append("1 ");
    180187        } else {
    181           strBuilder.Append("c_{" + constants.Count + "} ");
    182           constants.Add(constNode.Value);
    183         }
     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) + " )");
    184212      } else if (node.Symbol is LaggedVariable) {
    185213        var laggedVarNode = node as LaggedVariableTreeNode;
    186214        if (!laggedVarNode.Weight.IsAlmost(1.0)) {
    187           strBuilder.Append("c_{" + constants.Count + "} \\cdot ");
    188           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++;
    189219        }
    190220        strBuilder.Append(EscapeLatexString(laggedVarNode.VariableName));
     
    194224        var varNode = node as VariableTreeNode;
    195225        if (!varNode.Weight.IsAlmost((1.0))) {
    196           strBuilder.Append("c_{" + constants.Count + "} \\cdot ");
    197           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++;
    198230        }
    199231        strBuilder.Append(EscapeLatexString(varNode.VariableName));
     
    229261      } else if (node.Symbol is VariableCondition) {
    230262        var conditionTreeNode = node as VariableConditionTreeNode;
    231         string p = @"1 /  1 + \exp  - c_{" + constants.Count + "} ";
    232         constants.Add(conditionTreeNode.Slope);
    233         p += @" \cdot " + EscapeLatexString(conditionTreeNode.VariableName) + LagToString(currentLag) + " - c_{" + constants.Count + @"}   ";
    234         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++;
    235271        strBuilder.Append(@" \left( " + p + @"\cdot ");
    236272      } else {
     
    323359      } else if (node.Symbol is VariableCondition) {
    324360        var conditionTreeNode = node as VariableConditionTreeNode;
    325         string p = @"1 / \left( 1 + \exp \left( - c_{" + constants.Count + "} ";
    326         constants.Add(conditionTreeNode.Slope);
    327         p += @" \cdot " + EscapeLatexString(conditionTreeNode.VariableName) + LagToString(currentLag) + " - c_{" + constants.Count + @"} \right) \right) \right)   ";
    328         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++;
    329369        strBuilder.Append(@" +  \left( 1 - " + p + @" \right) \cdot ");
    330370      } else {
     
    404444      } else if (node.Symbol is LaggedVariable) {
    405445      } else if (node.Symbol is Variable) {
     446      } else if (node.Symbol is FactorVariable) {
     447      } else if (node.Symbol is BinaryFactorVariable) {
    406448      } else if (node.Symbol is ProgramRootSymbol) {
    407449        strBuilder
     
    411453        // output all constant values
    412454        if (constants.Count > 0) {
    413           int i = 0;
    414455          foreach (var constant in constants) {
    415456            // replace "." with ".&" to align decimal points
    416             var constStr = string.Format(System.Globalization.NumberFormatInfo.InvariantInfo, "{0:G5}", constant);
     457            var constStr = string.Format(System.Globalization.NumberFormatInfo.InvariantInfo, "{0:G5}", constant.Value);
    417458            if (!constStr.Contains(".")) constStr = constStr + ".0";
    418459            constStr = constStr.Replace(".", "&.");  // fix problem in rendering of aligned expressions
    419             strBuilder.Append("c_{" + i + "}& = & " + constStr);
     460            strBuilder.Append(constant.Key + "& = & " + constStr);
    420461            strBuilder.Append(@"\\");
    421             i++;
    422462          }
    423463        }
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Formatters/SymbolicDataAnalysisExpressionMATLABFormatter.cs

    r14185 r14826  
    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("(");
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Formatters/SymbolicDataAnalysisExpressionMathematicaFormatter.cs

    r14185 r14826  
    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.");
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Formatters/SymbolicDataAnalysisExpressionSmalltalkFormatter.cs

    r14185 r14826  
    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.