Free cookie consent management tool by TermsFeed Policy Generator

Changeset 9305


Ignore:
Timestamp:
03/11/13 14:40:04 (12 years ago)
Author:
fschoepp
Message:

#1888:

  • Added an Update / GetExperiment... methods to the controller for updating and querying experiments.
  • The AlgorithmConverter class now properly converts from/to JSON format.
  • Integrated backbone js as MVC provider for JavaScript + jquery.
  • Added experiment.model.js + experiment.view.js + experiment.controller.js containing the MVC impl. for the Experiment pages.
  • Added new methods to the ExperimentController usable by the backbone js model implementation.
  • Added the experiment dialog from HL 3.3.7 (variate experiment parameters). It's capable of variating the algorithm parameters.
Location:
branches/OaaS
Files:
10 added
21 edited

Legend:

Unmodified
Added
Removed
  • branches/OaaS/HeuristicLab.Services.Optimization.Controller/Azure/DAL.cs

    r9227 r9305  
    101101    }
    102102
    103     public ExperimentEntity(string user, string experimentName, string experimentUrl) {
     103    public ExperimentEntity(string user, string experimentName, string experimentId, string experimentUrl) {
    104104      PartitionKey = "ScenarioPartition";
    105105      RowKey = user + "_" + experimentName;     
    106106      User = user;
     107      ExperimentId = experimentId;
    107108      ExperimentJsonUrl = experimentUrl;
    108109    }
     110
     111    public string ExperimentId { get; set; }
    109112
    110113    public string User { get; set; }
     
    122125        return false;
    123126
    124       // TODO: Save the whole experiment, not just the algorithm names!!!
    125127      CloudBlobContainer container = BlobClient.GetContainerReference(AzureConstants.EXPERIMENT_BLOB_CONTAINER);
    126128      container.CreateIfNotExist();
    127129      // For now we store it as JSON element in the blob store
    128       // TODO: Make sure, that all required properties are part of the experiment!!
    129       var experimentJson = AlgorithmConverter.ConvertJson(experiment);
     130      var experimentJson = AlgorithmConverter.ConvertExperimentToJson(experiment);
    130131      Guid experimentJsonGuid = Guid.NewGuid();
    131132      var experimentJsonId = experiment.Name + "_" + experimentJsonGuid.ToString();
     133      experimentJson["nodeId"] = experimentJsonId.ToString();
    132134      var blob = container.GetBlobReference(experimentJsonId);     
    133       blob.UploadText(experimentJson);
     135      blob.UploadText(experimentJson.ToString());
     136      experiment.Id = experimentJsonId;
    134137
    135138      TableServiceContext serviceContext = TableClient.GetDataServiceContext();     
    136139      TableClient.CreateTableIfNotExist(AzureConstants.EXPERIMENT_TABLE);
    137       var entity = new ExperimentEntity(username, experiment.Name, blob.Uri.ToString());
     140      var entity = new ExperimentEntity(username, experiment.Name, experiment.Id, blob.Uri.ToString());
    138141      serviceContext.AddObject(AzureConstants.EXPERIMENT_TABLE, entity);
    139142      serviceContext.SaveChangesWithRetries();
     143      return true;
     144    }
     145
     146    public bool Update(string username, Experiment experiment) {
     147      TableServiceContext serviceContext = TableClient.GetDataServiceContext();
     148      TableClient.CreateTableIfNotExist(AzureConstants.EXPERIMENT_TABLE);
     149      var entity = (from e in serviceContext.CreateQuery<ExperimentEntity>(AzureConstants.EXPERIMENT_TABLE)
     150                    where e.ExperimentId == experiment.Id
     151                    select e).FirstOrDefault();
     152      if (entity == null) {
     153        return false;
     154      }
     155
     156      CloudBlobContainer container = BlobClient.GetContainerReference(AzureConstants.EXPERIMENT_BLOB_CONTAINER);
     157      container.CreateIfNotExist();
     158      var blob = container.GetBlobReference(entity.ExperimentJsonUrl);
     159      var experimentJson = AlgorithmConverter.ConvertExperimentToJson(experiment).ToString();
     160      blob.UploadText(experimentJson);
    140161      return true;
    141162    }
     
    177198      container.CreateIfNotExist();
    178199      var blob = container.GetBlobReference(entity.ExperimentJsonUrl);
    179       return AlgorithmConverter.ConvertExperimentSimple(blob.DownloadText());
     200      return AlgorithmConverter.ConvertJsonToExperiment(blob.DownloadText());
    180201    }
    181202
     
    199220      foreach (var entity in entites) {
    200221        var blob = container.GetBlobReference(entity.ExperimentJsonUrl);
    201         experiments.Add(AlgorithmConverter.ConvertExperimentSimple(blob.DownloadText()));
     222        experiments.Add(AlgorithmConverter.ConvertJsonToExperiment(blob.DownloadText()));
    202223      }
    203224      return experiments;
     
    218239      container.CreateIfNotExist();
    219240      var blob = container.GetBlobReference(entity.ExperimentJsonUrl);
    220       var exp = AlgorithmConverter.ConvertExperimentSimple(blob.DownloadText());
     241      var exp = AlgorithmConverter.ConvertJsonToExperiment(blob.DownloadText());
    221242      return exp;
    222243    }
     244
     245
     246    public Experiment GetExperimentById(User user, string nodeId) {
     247      TableServiceContext serviceContext = TableClient.GetDataServiceContext();
     248      TableClient.CreateTableIfNotExist(AzureConstants.EXPERIMENT_TABLE);
     249      var entity = (from e in serviceContext.CreateQuery<ExperimentEntity>(AzureConstants.EXPERIMENT_TABLE)
     250                    where e.ExperimentId == nodeId
     251                    select e).FirstOrDefault();
     252      if (entity == null || entity.ExperimentJsonUrl == null) {
     253        return null;
     254      }
     255
     256      if (entity.User != user.Username)
     257        return null;
     258
     259      CloudBlobContainer container = BlobClient.GetContainerReference(AzureConstants.EXPERIMENT_BLOB_CONTAINER);
     260      container.CreateIfNotExist();
     261      var blob = container.GetBlobReference(entity.ExperimentJsonUrl);
     262      return AlgorithmConverter.ConvertJsonToExperiment(blob.DownloadText());
     263    }
     264
    223265  }
    224266
  • branches/OaaS/HeuristicLab.Services.Optimization.Controller/HL/HiveScenarioManager.cs

    r9227 r9305  
    9797        foreach (var child in entry.Children) {
    9898          // This is a template experiment;
    99           if (child.Name == null) {
    100             var parent = new HeuristicLab.Optimization.Experiment(child.Name);
     99          if (child.IsExperiment) {
     100            var parent = new HeuristicLab.Optimization.Experiment();
    101101            entry.Parent.Optimizers.Add(parent);
    102102            stack.Push(new StackEntry() { Parent = parent, Children = child.ChildAlgorithms });         
     
    104104          // This entity is mapable
    105105          else {           
    106             IScenarioMapper mapper = GetMapper(child.Name);
    107             if (mapper == null) { // TODO: We should really be able to difference Experiment/Algorithm types; this is a workaround
    108               var parent = new HeuristicLab.Optimization.Experiment(child.Name);
    109               entry.Parent.Optimizers.Add(parent);
    110               stack.Push(new StackEntry() { Parent = parent, Children = child.ChildAlgorithms });         
    111             }
    112             else {
    113               var optScen = new OptimizationScenario() { Id = child.Name };
    114               optScen.Algorithm.Add(child);
    115               IAlgorithm algo;
    116               mapper.MapScenario(optScen, out algo);
    117               entry.Parent.Optimizers.Add(algo);
    118             }
     106            IScenarioMapper mapper = GetMapper(child.Id);
     107            var optScen = new OptimizationScenario() { Id = child.Id };
     108            optScen.Algorithm.Add(child);
     109            IAlgorithm algo;
     110            mapper.MapScenario(optScen, out algo);
     111            entry.Parent.Optimizers.Add(algo);
    119112          } 
    120113        }
     
    166159    private IScenarioMapper GetMapper(string scenarioId) {
    167160      var id = scenarioId;
    168       if (!mappers.ContainsKey(id)) {
     161      IScenarioMapper mapper = null;     
     162      if (!mappers.TryGetValue(id, out mapper)) {
    169163        lock (lockable) {
    170164          if (mappers.ContainsKey(id))
     
    173167          var mapperString = GetMapperFromBlobStore(id);
    174168          if (mapperString == null) return null;
    175           var mapper = CompileMapper(mapperString);
     169          mapper = CompileMapper(mapperString);
    176170
    177171          mappers[id] = mapper;
     
    179173        } // lock       
    180174       } // if
    181       return null;
     175      return mapper;
    182176     } 
    183177
     
    471465    }
    472466
    473     public bool SaveExperiment(User user, Model.Experiment experiment) {
    474       return dal.ExperimentDao.Add(user.Username, experiment);
    475     }
    476 
    477     public IEnumerable<string> GetExperiments(User user) {
     467    public string SaveExperiment(User user, Model.Experiment experiment) {
     468      if (experiment.Id != null) {
     469        dal.ExperimentDao.Update(user.Username, experiment);
     470      }
     471      else {
     472        dal.ExperimentDao.Add(user.Username, experiment);
     473      }
     474      return experiment.Id;
     475    }
     476
     477    public IEnumerable<string> GetExperimentNames(User user) {
    478478      return (from exp in dal.ExperimentDao.GetExperiments(user.Username)
    479479              select exp.Name);
     
    564564    }
    565565
    566 
    567 
     566    public IEnumerable<Model.Experiment> GetExperiments(User user) {
     567      return dal.ExperimentDao.GetExperiments(user.Username);
     568    }
     569
     570    public Model.Experiment GetExperimentById(User user, string nodeId) {
     571      return dal.ExperimentDao.GetExperimentById(user, nodeId);
     572    }
    568573  }
    569574}
  • branches/OaaS/HeuristicLab.Services.Optimization.Controller/HeuristicLab.Services.Optimization.ControllerService.csproj

    r9227 r9305  
    189189  </ItemGroup>
    190190  <ItemGroup>
    191     <None Include="packages.config" />
     191    <None Include="packages.config">
     192      <SubType>Designer</SubType>
     193    </None>
    192194  </ItemGroup>
    193195  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  • branches/OaaS/HeuristicLab.Services.Optimization.Controller/Interfaces/DAL.cs

    r9227 r9305  
    2020  public interface IExperimentDao {
    2121    bool Add(string username, Experiment experiment);
     22    bool Update(string username, Experiment experiment);
    2223    bool DeleteByName(string username, string experiment);
    2324    Experiment FindByName(string username, string experiment);
    2425    IEnumerable<Experiment> GetExperiments(string user);
    2526    Experiment GetExperimentByName(string username, string scenario);
     27
     28    Experiment GetExperimentById(User user, string nodeId);
    2629  }
    2730
  • branches/OaaS/HeuristicLab.Services.Optimization.Controller/Interfaces/IControllerService.cs

    r9227 r9305  
    4444
    4545    [OperationContract]
    46     bool SaveExperiment(User user, Experiment experiment);
     46    string SaveExperiment(User user, Experiment experiment);
    4747
    4848    [OperationContract]
    49     IEnumerable<string> GetExperiments(User user);
     49    IEnumerable<string> GetExperimentNames(User user);
     50
     51    [OperationContract]
     52    IEnumerable<Experiment> GetExperiments(User user);
    5053
    5154    [OperationContract]
     
    6063    [OperationContract]
    6164    Experiment GetExperimentByName(User user, string scenario);
     65
     66    [OperationContract]
     67    Experiment GetExperimentById(User u, string nodeId);
    6268  }
    6369}
  • branches/OaaS/HeuristicLab.Services.Optimization.Controller/Interfaces/IScenarioManager.cs

    r9227 r9305  
    1515    bool DeleteScenario(User user, string scenarioName);
    1616
    17     bool SaveExperiment(User user, Experiment experiment);
    18     IEnumerable<string> GetExperiments(User user);
     17    string SaveExperiment(User user, Experiment experiment);
     18    IEnumerable<string> GetExperimentNames(User user);
     19    IEnumerable<Model.Experiment> GetExperiments(User user);
     20    Experiment GetExperimentByName(User user, string scenario);
     21    Experiment GetExperimentById(User user, string nodeId);
     22
    1923    bool DeleteExperiment(User user, string experiment);
    2024
     
    2226    Job GetTasks(User u, string jobId);
    2327
    24     Experiment GetExperimentByName(User user, string scenario);
     28   
    2529    bool DispatchExperiment(User user, Experiment exp, JobExecutionDetails details);
    2630  }
  • branches/OaaS/HeuristicLab.Services.Optimization.Controller/Interfaces/Model/ControllerModel.cs

    r9227 r9305  
    277277
    278278    [DataMember]
     279    public string Id { get; set; }
     280
     281    [DataMember]
    279282    public AlgorithmParameters Parameters { get; set; }
    280283
     
    293296    [DataMember]
    294297    public string Name { get; set; }
     298
     299    [DataMember]
     300    public bool IsExperiment { get; set; }
    295301  }
    296302
     
    315321    [DataMember]
    316322    public IList<Algorithm> Algorithm { get; set; }
     323
     324    [DataMember]
     325    public string Id { get; set; }
    317326
    318327    public Experiment() {
  • branches/OaaS/HeuristicLab.Services.Optimization.Controller/Mockup/MockupScenarioManager.cs

    r9227 r9305  
    241241
    242242
    243     public bool SaveExperiment(User user, Model.Experiment experiment) {
    244       throw new NotImplementedException();
    245     }
    246 
    247 
    248     public IEnumerable<string> GetExperiments(User user) {
     243    public string SaveExperiment(User user, Model.Experiment experiment) {
     244      throw new NotImplementedException();
     245    }
     246
     247
     248    public IEnumerable<string> GetExperimentNames(User user) {
    249249      throw new NotImplementedException();
    250250    }
     
    271271
    272272    public bool DispatchExperiment(User user, Model.Experiment exp, JobExecutionDetails details) {
     273      throw new NotImplementedException();
     274    }
     275
     276
     277    string IScenarioManager.SaveExperiment(User user, Model.Experiment experiment) {
     278      throw new NotImplementedException();
     279    }
     280
     281    public IEnumerable<Model.Experiment> GetExperiments(User user) {
     282      throw new NotImplementedException();
     283    }
     284
     285    public Model.Experiment GetExperimentById(User user, string nodeId) {
    273286      throw new NotImplementedException();
    274287    }
  • branches/OaaS/HeuristicLab.Services.Optimization.Controller/Parsers/AlgorithmConverter.cs

    r9227 r9305  
    99namespace HeuristicLab.Services.Optimization.ControllerService.Parsers {
    1010  public static class AlgorithmConverter {
    11 
    12     public static Algorithm Convert(string json) {
    13       var o = JObject.Parse(json);
    14       return ParseAlgorithm(o);     
    15     }
    16 
    17     private static Algorithm ParseAlgorithm(JToken obj) {
    18       var algorithm = new Algorithm();
    19 
    20       foreach (JProperty param in obj["Algorithm Parameters"]) {
    21         Parameter parameter = CreateParameter(param);
    22         algorithm.Parameters.Items.Add(parameter);
    23       }
    24 
    25       var problemParams = obj["Problem Parameters"];
    26       if (problemParams != null) {
    27         algorithm.Problem = new Problem();
    28         foreach (JProperty param in problemParams) {
    29           Parameter parameter = CreateParameter(param);
    30           algorithm.Problem.Parameters.Items.Add(parameter);
    31         }
    32       }
    33       return algorithm;
    34     }
    35 
    36     public static Algorithm ConvertAppend(string json, Algorithm algorithm) {
    37       var o = JObject.Parse(json);
    38       foreach (JProperty param in o["Algorithm Parameters"]) {
    39         Parameter parameter = CreateParameter(param);
    40         var oldParameter = (from p in algorithm.Parameters.Items where p.Value.Name == parameter.Value.Name select p).FirstOrDefault();
    41         if (oldParameter != null) {
    42           oldParameter.Value = parameter.Value;
    43         }
    44         else {
    45           algorithm.Parameters.Items.Add(parameter);
    46         }
    47       }
    48 
    49       var problemParams = o["Problem Parameters"];
    50       if (problemParams != null) {
    51         algorithm.Problem = new Problem();
    52         foreach (JProperty param in problemParams) {
    53           Parameter parameter = CreateParameter(param);         
    54           var oldParameter = (from p in algorithm.Problem.Parameters.Items where p.Value.Name == parameter.Value.Name select p).FirstOrDefault();
    55           if (oldParameter != null) {
    56             oldParameter.Value = parameter.Value;
    57           }
    58           else {
    59             algorithm.Problem.Parameters.Items.Add(parameter);
    60           }
    61         }
    62       }
    63       return algorithm;
    64     }
    65 
    66     private static Parameter CreateParameter(JProperty property) {
    67       JToken token = property.Value;
    68       switch (token.Type) {
     11    #region private methods
     12    private static Parameter CreateParameter(JObject property) {
     13      var name = (string)property["Name"];
     14      var value = property["Value"];
     15      switch (value.Type) {
    6916        case JTokenType.Integer:
    7017        case JTokenType.Float:
    71           return new Parameter() { Type = ParameterType.Decimal, Value = new DecimalValue() { Name = property.Name, Value = (double)property.Value } };
     18          return new Parameter() { Type = ParameterType.Decimal, Value = new DecimalValue() { Name = name, Value = (double)value } };
    7219        case JTokenType.Boolean:
    73           return new Parameter() { Type = ParameterType.Boolean, Value = new BoolValue() { Name = property.Name, Value = (bool)property.Value } };
     20          return new Parameter() { Type = ParameterType.Boolean, Value = new BoolValue() { Name = name, Value = (bool)value } };
    7421        case JTokenType.String:
    75           return new Parameter() { Type = ParameterType.Type, Value = new TypeValue() { Name = property.Name, Value = (string)property.Value } };                 
     22          return new Parameter() { Type = ParameterType.Type, Value = new TypeValue() { Name = name, Value = (string)value, Options = (from e in property["Options"] select (string)e).ToArray() } };
    7623        case JTokenType.Array:
    77           var arr = (JArray)token;
     24          var arr = (JArray)value;
    7825          // its a matrix
    7926          if (arr[0].Type == JTokenType.Array) {
    80             return CreateMatrixParameter(property.Name, arr);
     27            return CreateMatrixParameter(name, arr);
    8128          }
    82           return CreateVectorParameter(property.Name, arr);
     29          return CreateVectorParameter(name, arr);
    8330        default:
    8431          throw new Exception("Unhandled datatype: " + property.Type);
     
    8936      double[][] entries = new double[arr.Count][];
    9037      for (int i = 0; i < entries.Length; i++) {
    91         entries[i] = (from d in arr[i] select (double)d).ToArray<double>(); 
     38        entries[i] = (from d in arr[i] select (double)d).ToArray<double>();
    9239      }
    9340      return new Parameter { Type = ParameterType.DecimalMatrix, Value = new DecimalMatrix() { Name = name, Value = entries } };
     
    9946    }
    10047
    101     public static string ConvertJson(Algorithm algorithm) {
    102       return JsonConvert.SerializeObject(algorithm);
    103     }
    104 
    105    
    10648    private class StackEntry {
    10749      public Algorithm Parent { get; set; }
     
    10951    }
    11052
    111     public static Experiment ConvertExperimentSimple(string json) {
    112       return JsonConvert.DeserializeObject<Experiment>(json, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Auto });
    113     }
    114 
    115     public static string ConvertJson(Experiment experiment) {
    116       return JsonConvert.SerializeObject(experiment, Formatting.None, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto });
    117     }
    118 
    119     public static Experiment ConvertExperiment(string json) {
     53    private static JArray ConvertParametersToJson(IList<Parameter> parameters) {
     54      var array = new JArray();
     55      foreach (var param in parameters) {
     56        array.Add(JObject.FromObject(param.Value));
     57      }
     58      return array;
     59    }
     60
     61    private struct Entry {
     62      public JObject TargetAlgorithm { get; set; }
     63
     64      public Algorithm SourceAlgorithm { get; set; }
     65    }
     66
     67    private static Algorithm ParseAlgorithm(JToken jsonAlgorithm) {
     68      var algorithm = new Algorithm();
     69
     70      foreach (JObject param in jsonAlgorithm["AlgorithmParameters"]) {
     71        Parameter parameter = CreateParameter(param);
     72        algorithm.Parameters.Items.Add(parameter);
     73      }
     74
     75      var problemParams = jsonAlgorithm["ProblemParameters"];
     76      if (problemParams != null) {
     77        algorithm.Problem = new Problem();
     78        foreach (JObject param in problemParams) {
     79          Parameter parameter = CreateParameter(param);
     80          algorithm.Problem.Parameters.Items.Add(parameter);
     81        }
     82      }
     83      return algorithm;
     84    }
     85    #endregion
     86
     87
     88    #region public methods
     89
     90
     91    public static JObject ConvertExperimentToJson(Experiment experiment) {
     92      var exp = new JObject();
     93      exp["title"] = experiment.Name;
     94      exp["children"] = new JArray();
     95      exp["nodeId"] = experiment.Id;
     96      exp["isExperiment"] = true;
     97
     98      var stack = new Stack<Entry>();
     99      foreach (var algo in experiment.Algorithm)
     100        stack.Push(new Entry() { TargetAlgorithm = exp, SourceAlgorithm = algo });
     101
     102      while (stack.Count > 0) {
     103        var entry = stack.Pop();
     104        var algorithm = ConvertAlgorithmToJson(entry.SourceAlgorithm);
     105        (entry.TargetAlgorithm["children"] as JArray).Add(algorithm);
     106
     107        if (entry.SourceAlgorithm.ChildAlgorithms.Count > 0) {
     108          // push children
     109          foreach (var child in entry.SourceAlgorithm.ChildAlgorithms) {
     110            stack.Push(new Entry() { TargetAlgorithm = algorithm, SourceAlgorithm = child });
     111          }
     112        }
     113
     114      }
     115      return exp;
     116    }
     117
     118    public static JArray ConvertExperimentsToJson(IEnumerable<Experiment> experiments) {
     119      var jarray = new JArray();
     120      foreach (var exp in experiments)
     121        jarray.Add(ConvertExperimentToJson(exp));
     122      return jarray;
     123    }
     124
     125    public static JArray ConvertAlgorithmsToJson(IEnumerable<Algorithm> algorithms) {
     126      var jarray = new JArray();
     127      foreach (var algo in algorithms)
     128        jarray.Add(ConvertAlgorithmToJson(algo));
     129      return jarray;
     130    }
     131
     132
     133    public static JArray ConvertScenariosToJson(IEnumerable<OptimizationScenario> scenarios) {
     134      var jarray = new JArray();
     135      foreach (var scen in scenarios)
     136        jarray.Add(ConvertScenarioToJson(scen));
     137      return jarray;
     138    }
     139
     140    public static JObject ConvertScenarioToJson(OptimizationScenario scenario) {
     141      var exp = new JObject();
     142      exp["title"] = scenario.Id;
     143      exp["children"] = new JArray();
     144      exp["nodeId"] = scenario.Id;
     145      exp["isExperiment"] = false;
     146
     147      var stack = new Stack<Entry>();
     148      var baseAlgorithm = ConvertAlgorithmToJson(scenario.FirstAlgorithm);
     149      exp["data"] = baseAlgorithm["data"];
     150      if (scenario.FirstAlgorithm.ChildAlgorithms.Count > 0) {
     151        foreach (var child in scenario.FirstAlgorithm.ChildAlgorithms)
     152          stack.Push(new Entry() { TargetAlgorithm = exp, SourceAlgorithm = child});
     153      }
     154
     155      while (stack.Count > 0) {
     156        var entry = stack.Pop();
     157        var algorithm = ConvertAlgorithmToJson(entry.SourceAlgorithm);
     158        (entry.TargetAlgorithm["children"] as JArray).Add(algorithm);
     159
     160        if (entry.SourceAlgorithm.ChildAlgorithms.Count > 0) {
     161          // push children
     162          foreach (var child in entry.SourceAlgorithm.ChildAlgorithms) {
     163            stack.Push(new Entry() { TargetAlgorithm = algorithm, SourceAlgorithm = child });
     164          }
     165        }
     166
     167      }
     168      return exp;
     169    }
     170
     171    public static JObject ConvertAlgorithmToJson(Algorithm algorithm) {
     172      var jalgo = new JObject();
     173      jalgo["title"] = algorithm.Name;
     174      jalgo["nodeId"] = algorithm.Id;
     175      var jalgoData = new JObject();
     176      jalgo["data"] = jalgoData;
     177      jalgo["isExperiment"] = algorithm.IsExperiment;
     178      jalgoData["AlgorithmParameters"] = ConvertParametersToJson(algorithm.Parameters.Items);
     179      if (algorithm.Problem != null && algorithm.Problem.Parameters != null)
     180        jalgoData["ProblemParameters"] = ConvertParametersToJson(algorithm.Problem.Parameters.Items);
     181
     182      jalgo["children"] = new JArray();
     183      return jalgo;
     184    }
     185
     186    public static Experiment ConvertJsonToExperiment(string json) {
    120187      var experiment = new Experiment();
    121188      var jsonExperiment = JObject.Parse(json);
    122       experiment.Name = (string)jsonExperiment["name"];
     189      experiment.Name = (string)jsonExperiment["title"];
     190      experiment.Id = (string)jsonExperiment["nodeId"];     
    123191      var stack = new Stack<StackEntry>();
    124192      var root = new Algorithm();
    125193
    126       if ((bool)jsonExperiment["run"]) {
     194      if (jsonExperiment["run"] != null && (bool)jsonExperiment["run"]) {
    127195        experiment.JobDetails = new JobExecutionDetails() {
    128            Group = (string)jsonExperiment["group"],
    129            Repititions = (int)jsonExperiment["repititions"]
     196          Group = (string)jsonExperiment["group"],
     197          Repititions = (int)jsonExperiment["repititions"]
    130198        };
    131199      }
    132200
    133       foreach (var algo in jsonExperiment["algorithms"]["children"]) {
    134         stack.Push(new StackEntry(){ Parent = root, Child = algo });
    135       }
     201      // ignore experiment node, skip to its children
     202      if (jsonExperiment["experiment"] != null)
     203        foreach (var algo in jsonExperiment["experiment"]["children"]) {
     204          stack.Push(new StackEntry() { Parent = root, Child = algo });
     205        }
     206
     207      if (jsonExperiment["children"] != null)
     208        foreach (var algo in jsonExperiment["children"]) {
     209          stack.Push(new StackEntry() { Parent = root, Child = algo });
     210        }
    136211
    137212      while (stack.Count > 0) {
    138213        var entry = stack.Pop();
    139214        var data = entry.Child["data"];
    140         var currentAlgo = data == null ? new Algorithm() : ParseAlgorithm(entry.Child["data"]);
    141         currentAlgo.Name = (string)entry.Child["name"];
     215        var currentAlgo = data == null || !data.HasValues ? new Algorithm() : ParseAlgorithm(entry.Child["data"]);
     216        currentAlgo.Name = (string)entry.Child["title"];
     217        currentAlgo.Id = (string)entry.Child["nodeId"];
     218        currentAlgo.IsExperiment = (bool)entry.Child["isExperiment"];
    142219        entry.Parent.ChildAlgorithms.Add(currentAlgo);
    143220        // push children on stack (inverse order to preserve ordering)
    144221        var cnt = entry.Child["children"].Count();
    145         for (var i=0; i < cnt; i++) {
     222        for (var i = 0; i < cnt; i++) {
    146223          stack.Push(new StackEntry() { Parent = currentAlgo, Child = entry.Child["children"][cnt - 1 - i] });
    147224        }
     
    154231      return experiment;
    155232    }
     233    #endregion
    156234  }
    157235}
  • branches/OaaS/HeuristicLab.Services.Optimization.Controller/PlaceholderControllerService.cs

    r9227 r9305  
    121121
    122122
    123     public bool SaveExperiment(User user, Experiment experiment) {     
     123    public string SaveExperiment(User user, Experiment experiment) {     
    124124      // make sure all algorithms store their choices aswell
    125125      var scenarioMap = new Dictionary<string, OptimizationScenario>();
     
    146146
    147147      // finally store the experiment
    148       var success = hiveManager.SaveExperiment(user, experiment);
     148      var id = hiveManager.SaveExperiment(user, experiment);
    149149      // if it has been stored, and jobdetails are present, run the job!
    150       if (success && experiment.JobDetails != null) {
    151         return ScheduleExperiment(user, experiment.Name, experiment.JobDetails);
     150      if (id != null && experiment.JobDetails != null) {
     151        ScheduleExperiment(user, experiment.Id, experiment.JobDetails);
    152152      }
    153       return success;
     153      return id;
    154154    }
    155155
    156156
    157     public IEnumerable<string> GetExperiments(User user) {
    158       return hiveManager.GetExperiments(user);
     157    public IEnumerable<string> GetExperimentNames(User user) {
     158      return hiveManager.GetExperimentNames(user);
    159159    }
    160160
     
    179179
    180180
    181     public bool ScheduleExperiment(User user, string experiment, JobExecutionDetails details) {
    182       var exp = hiveManager.GetExperimentByName(user, experiment);
     181    public bool ScheduleExperiment(User user, string experimentId, JobExecutionDetails details) {
     182      var exp = hiveManager.GetExperimentById(user, experimentId);
    183183      return hiveManager.DispatchExperiment(user, exp, details);
     184    }
     185
     186
     187    public IEnumerable<Experiment> GetExperiments(User user) {
     188      return hiveManager.GetExperiments(user);
     189    }
     190
     191    public Experiment GetExperimentById(User u, string nodeId) {
     192      return hiveManager.GetExperimentById(u, nodeId);
    184193    }
    185194  }
  • branches/OaaS/HeuristicLab.Services.Optimization.Controller/packages.config

    r9062 r9305  
    11<?xml version="1.0" encoding="utf-8"?>
    2 <packages>
     2<packages> 
    33  <package id="Newtonsoft.Json" version="4.5.11" />
    44</packages>
  • branches/OaaS/HeuristicLab.Services.Optimization.Web/Binders/AlgorithmJsonAttribute.cs

    r9227 r9305  
    1313namespace Mvc3TestApplication.Binders
    1414{
    15   public class AlgorithmJsonAttribute : CustomModelBinderAttribute
    16   {
    17     public override IModelBinder GetBinder()
    18     {
    19       return new AlgorithmJsonBinder();
    20     }
    21   }
    22 
    23   public class AlgorithmJsonBinder : IModelBinder
    24   {
    25     public AlgorithmJsonBinder()
    26     {
    27     }
    28 
    29     public object BindModel(ControllerContext controllerCtx, ModelBindingContext bindingCtx)
    30     {
    31       var contentType = controllerCtx.HttpContext.Request.ContentType;
    32       if (!contentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
    33         return null;
    34 
    35       string body;
    36       using (var stream = controllerCtx.HttpContext.Request.InputStream)
    37       {
    38         stream.Seek(0, System.IO.SeekOrigin.Begin);
    39         using (var reader = new StreamReader(stream))
    40           body = reader.ReadToEnd();
    41       }
    42       if (string.IsNullOrEmpty(body)) return null;
    43       return AlgorithmConverter.Convert(body);
    44     }
    45 
    46    
    47   }
    48 
    4915  public class ExperimentJsonAttribute : CustomModelBinderAttribute {
    5016    public override IModelBinder GetBinder() {
     
    6935      }
    7036      if (string.IsNullOrEmpty(body)) return null;
    71       return AlgorithmConverter.ConvertExperiment(body);
     37      return AlgorithmConverter.ConvertJsonToExperiment(body);
    7238    }
    7339
  • branches/OaaS/HeuristicLab.Services.Optimization.Web/Content/Site.css

    r9215 r9305  
    356356  border: 1px solid black;
    357357}
     358
     359
     360.leftEntry {
     361    float: left;
     362    width: 30%;
     363}
     364
     365.rightEntry{
     366    margin-left: 30%;
     367}
  • branches/OaaS/HeuristicLab.Services.Optimization.Web/Content/hl/Site.css

    r9215 r9305  
    433433    display: none;
    434434}
     435
     436.leftEntry {
     437    float: left;
     438    width: 30%;
     439}
     440
     441.rightEntry{
     442    margin-left: 30%;
     443}
     444
     445.ui-selected
     446{
     447    background: #EA8511; 
     448}
  • branches/OaaS/HeuristicLab.Services.Optimization.Web/Content/smartwizard2.0/styles/smart_wizard.css

    r9227 r9305  
    9292  list-style: none;
    9393  padding: 0px; 
    94   margin: 10px 0;     
     94  /*margin: 10px 0;*/       
    9595  clear: both;
    9696  border: 0px solid #CCCCCC;   
     
    112112  position:relative;
    113113  float:left;
    114   margin:0;
     114  margin: 10px 0;
    115115  padding:3px;
    116116  height:60px;
  • branches/OaaS/HeuristicLab.Services.Optimization.Web/Controllers/ExperimentController.cs

    r9227 r9305  
    3131        public ActionResult Index()
    3232        {
    33           var model = new ExperimentViewModel();
     33          return RedirectToAction("New");
     34          /*var model = new ExperimentViewModel();
    3435          var scenarios = ControllerService.withControllerService<IEnumerable<string>>((service) => {
    3536            return service.GetOptimizationScenarioNames();
     
    3738          var experiments = ControllerService.withControllerService<IEnumerable<string>>((service) => {
    3839            User u = new User() { Username = Membership.GetUser().UserName, Password = Session["pw"] as string };
    39             return service.GetExperiments(u);
     40            return service.GetExperimentNames(u);
    4041          });
    4142          foreach (var experiment in experiments)
     
    4445            model.Scenarios.Add(scenario);
    4546
    46           Session["experiment"] = new Experiment();
    47 
    48           return View(model);
     47          return View(model);*/
    4948        }
    5049
    5150        public ActionResult New() {
    52           return Index();
     51          return View();
    5352        }
    5453
    55         public Experiment Experiment { get { return Session["experiment"] as Experiment; } set { Session["experiment"] = value;} }
    56 
    57         [HttpPost]
    58         public JsonResult Save(ExperimentModel model) {
    59           var experiment = new Experiment() { Name = model.Name };
    60           var stack = new Stack<Node>();
    61 
    62           foreach (var node in model.Experiment.children)
    63             stack.Push(node);
    64 
    65           while (stack.Count > 0) {
    66             var currentNode = stack.Pop();
    67             // add children to stack
    68             if (currentNode.children != null)
    69               foreach (var node in currentNode.children)
    70                 stack.Push(node);
    71 
    72             // TODO: Do we really need a tree of scenarios? Or is it a simple list?
    73             // push currentNode to experiment
    74             if (currentNode.title == "Experiment")
    75               continue;
    76             experiment.Algorithm.Add(new Algorithm() { Name = currentNode.title });
    77           }
    78 
    79           var ok = ControllerService.withControllerService<bool>((service) => {
    80             User u = new User() { Username = Membership.GetUser().UserName, Password = Session["pw"] as string };
    81             return service.SaveExperiment(u, experiment);
    82           });
    83 
    84           if (ok)
    85             return Json(new { success = true, data = model.Name });
    86           return Json(new { success = false, error = "Experiment already exists!" });
     54        public ActionResult NewEdit() {
     55          return View();
    8756        }
    8857
     
    9160          var experiments = ControllerService.withControllerService<IEnumerable<string>>((service) => {
    9261            User u = new User() { Username = Membership.GetUser().UserName, Password = Session["pw"] as string };
    93             return service.GetExperiments(u);
     62            return service.GetExperimentNames(u);
    9463          });
    9564          foreach (var experiment in experiments)
     
    10675        }
    10776
    108         [HttpPost]
    109         public JsonResult SaveExperiment([ExperimentJson] Experiment experiment) {
    110           return Json(
    111             new {
    112               Success = ControllerService.withControllerService<bool>(service => {
     77      #region new experiment methdos
     78      [HttpGet]
     79      public ActionResult Scenario(string nodeId) {
     80        var optimizationScenario = ControllerService.withControllerService<OptimizationScenario>(service => {
     81          return service.GetOptimizationScenarioByName(nodeId);
     82        });
     83        return Content(AlgorithmConverter.ConvertScenarioToJson(optimizationScenario).ToString(), "application/json", System.Text.Encoding.UTF8);
     84      }
     85
     86      [HttpGet]
     87      public ActionResult ExperimentList() {
     88        var experiments = ControllerService.withControllerService<IEnumerable<Experiment>>(service => {
     89          User u = new User() { Username = Membership.GetUser().UserName, Password = Session["pw"] as string };
     90          return service.GetExperiments(u);
     91        });
     92        return Content(AlgorithmConverter.ConvertExperimentsToJson(experiments).ToString(), "application/json", System.Text.Encoding.UTF8);
     93      }
     94
     95      [HttpGet]
     96      public ActionResult ScenarioList() {
     97        var scenarios = ControllerService.withControllerService<IEnumerable<OptimizationScenario>>(service => {
     98          User u = new User() { Username = Membership.GetUser().UserName, Password = Session["pw"] as string };
     99          return service.GetOptimizationScenarios();
     100        });
     101        return Content(AlgorithmConverter.ConvertScenariosToJson(scenarios).ToString(), "application/json", System.Text.Encoding.UTF8);
     102      }
     103
     104      [HttpPut]
     105      public JsonResult Experiment(string nodeId, [ExperimentJson] Experiment exp) {
     106        return Json(
     107            new {
     108              nodeId = ControllerService.withControllerService<string>(service => {
    113109                User u = new User() { Username = Membership.GetUser().UserName, Password = Session["pw"] as string };
    114                 return service.SaveExperiment(u, experiment);
     110                return service.SaveExperiment(u, exp);
    115111              })
    116112            });
    117         }
     113      }
    118114
    119         private JsonResult ComplexExperimentCase(string scenario) {
    120           // complex case, find children of experiment
    121           var model = new GetParametersModel() { Type = "Complex" };
    122           model.Subnames = new List<string>();
     115      [HttpPost]
     116      public JsonResult Experiment([ExperimentJson] Experiment exp) {
     117        return Json(
     118            new {
     119              nodeId = ControllerService.withControllerService<string>(service => {
     120                User u = new User() { Username = Membership.GetUser().UserName, Password = Session["pw"] as string };
     121                return service.SaveExperiment(u, exp);
     122              })
     123            });
     124      }
    123125
    124           var experiment = ControllerService.withControllerService<Experiment>(service => {
    125             User user = new User() { Username = Membership.GetUser().UserName, Password = Session["pw"] as string };
    126             return service.GetExperimentByName(user, scenario);
    127           });
    128126
    129           // TODO: Make a tree out of subnames!!
    130           if (experiment != null)
    131             foreach (var algo in experiment.Algorithm)
    132               model.Subnames.Add(algo.Name);
    133 
    134           return Json(model, JsonRequestBehavior.AllowGet);
    135         }
    136 
    137         [HttpGet]
    138         public JsonResult GetParameters(string scenario, string context, int index) {
    139           if (context == "Experiment" || context == null) {
    140             var optimizationScenario = ControllerService.withControllerService<OptimizationScenario>(service => {
    141               return service.GetOptimizationScenarioByName(scenario);
    142             });
    143 
    144             if (optimizationScenario != null) {
    145               var model = new GetParametersModel() { Type = "Basic" };
    146               model.Algorithm = optimizationScenario.FirstAlgorithm;
    147               model.Algorithm.Mapper = optimizationScenario.Id;
    148               var json = Json(model, JsonRequestBehavior.AllowGet);
    149               return json;
    150             }
    151             else {
    152               // complex case, find children of experiment
    153               var model = new GetParametersModel() { Type = "Complex" };
    154               model.Subnames = new List<string>();
    155 
    156               var experiment = ControllerService.withControllerService<Experiment>(service => {
    157                 User user = new User() { Username = Membership.GetUser().UserName, Password = Session["pw"] as string };
    158                 return service.GetExperimentByName(user, scenario);
    159               });
    160 
    161               // TODO: Make a tree out of subnames!!
    162               if (experiment != null)
    163                 foreach (var algo in experiment.Algorithm)
    164                   model.Subnames.Add(algo.Name);
    165 
    166               return Json(model, JsonRequestBehavior.AllowGet);
    167             }
    168           }
    169           else {
    170             var experiment = ControllerService.withControllerService<Experiment>(service => {
    171               User u = new User() { Username = Membership.GetUser().UserName, Password = Session["pw"] as string };
    172               return service.GetExperimentByName(u, context);
    173             });
    174 
    175             // if child algorithm is a complex algorithm, return as such
    176             if (experiment.Algorithm[index].ChildAlgorithms.Count > 0) {
    177               var model = new GetParametersModel() { Type = "Complex" };
    178               model.Subnames = new List<string>();
    179               foreach (var algo in experiment.Algorithm[index].ChildAlgorithms)
    180                 model.Subnames.Add(algo.Name);
    181               return Json(model, JsonRequestBehavior.AllowGet);
    182             }
    183             else {
    184               // otherwise we have the algorithms just below it
    185               var model = new GetParametersModel() { Type = "Basic" };
    186               model.Algorithm = experiment.Algorithm[index];
    187               model.Algorithm.Mapper = experiment.Algorithm[index].Name;
    188               var json = Json(model, JsonRequestBehavior.AllowGet);
    189               return json;
    190             }
    191           }
    192         }
     127      [HttpGet]
     128      public ActionResult Experiment(string nodeId) {
     129        var experiment = ControllerService.withControllerService<Experiment>(service => {
     130          User u = new User() { Username = Membership.GetUser().UserName, Password = Session["pw"] as string };
     131          return service.GetExperimentById(u, nodeId);
     132        });
     133        var str = AlgorithmConverter.ConvertExperimentToJson(experiment).ToString();
     134        return Content(str, "application/json", System.Text.Encoding.UTF8);
     135      }
     136      #endregion
    193137    }
    194138}
  • branches/OaaS/HeuristicLab.Services.Optimization.Web/HeuristicLab.Services.Optimization.Web.csproj

    r9227 r9305  
    5151      <HintPath>..\packages\WindowsAzure.Storage.1.7.0.0\lib\net35-full\Microsoft.WindowsAzure.StorageClient.dll</HintPath>
    5252    </Reference>
     53    <Reference Include="Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
     54      <HintPath>..\packages\Newtonsoft.Json.4.5.11\lib\net40\Newtonsoft.Json.dll</HintPath>
     55    </Reference>
    5356    <Reference Include="System.Data.Entity" />
    5457    <Reference Include="System.Data.Services.Client" />
     
    98101  <ItemGroup>
    99102    <Content Include="Content\ajax-loader.gif" />
     103    <Content Include="Content\backbone\backbone-min.js" />
     104    <Content Include="Content\backbone\backbone-relational.js" />
     105    <Content Include="Content\backbone\underscore-min.js" />
     106    <Content Include="Content\backbone\underscore.js" />
    100107    <Content Include="Content\Datatypemapping.js" />
    101108    <Content Include="Content\dynatree\dist\jquery.dynatree.min.js" />
     
    106113    <Content Include="Content\dynatree\src\skin\vline-rtl.gif" />
    107114    <Content Include="Content\dynatree\src\skin\vline.gif" />
     115    <Content Include="Content\experiment.controller.js" />
     116    <Content Include="Content\experiment.model.js" />
     117    <Content Include="Content\experiment.view.js" />
    108118    <Content Include="Content\ExperimentSupport.js" />
    109119    <Compile Include="Binders\AlgorithmJsonAttribute.cs" />
     
    373383    <Content Include="Views\Status\Index.cshtml" />
    374384    <Content Include="Views\Experiment\New.cshtml" />
     385    <Content Include="Views\Experiment\NewEdit.cshtml" />
    375386  </ItemGroup>
    376387  <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
  • branches/OaaS/HeuristicLab.Services.Optimization.Web/Views/Experiment/Index.cshtml

    r9215 r9305  
    6060@section submenu {
    6161    <ul>
    62         <li class="selected">@Html.ActionLink("Build", "Index")</li>   
    63         <li>@Html.ActionLink("Edit", "Edit")</li>
     62        <li class="selected">@Html.ActionLink("Build", "New")</li>   
     63        <li>@Html.ActionLink("Edit", "NewEdit")</li>
    6464        <li>@Html.ActionLink("Status", "Index", "Status")</li>
    6565    </ul>
  • branches/OaaS/HeuristicLab.Services.Optimization.Web/Views/Experiment/New.cshtml

    r9227 r9305  
    11@model HeuristicLab.Services.Optimization.Web.Models.ExperimentViewModel
    2 @{
    3     ViewBag.Title = "Index.cshtml";
    4 }
    5 
     2<script type="text/template" id="node_template">
     3  <li><%= title%></li> 
     4</script>
     5
     6<script type="text/template" id="tree_template">
     7  <div id="<%= id %>" class="treeStyle">
     8    <ul>     
     9    </ul>
     10  </div>
     11</script>
     12
     13<script type="text/template" id="draggable_template">
     14  <div id="<%= nodeId %>" data-isExperiment="<%= isExperiment%>" data-name="<%= title%>" class="dragables"><p><%= title %></p></div>
     15</script>
     16
     17<script type="text/template" id="stepwizard_template">
     18  <input style="margin-top:5px;" class="remove-button" name="RemoveNode" type="button" value="Remove" disabled="disabled" />
     19  <input style="margin-top:5px;" class="variate-button" name="VariateNode" type="button" value="Variate" disabled="disabled" />
     20</script>           
     21
     22<script type="text/template" id="parameter_template">
     23<div>
     24  <div class="leftEntry"><%= Name %>:</div>
     25  <div class="rightEntry"></div> 
     26</div>
     27</script>       
     28
     29<script type="text/template" id="validationhints_template">
     30<div class="validator" title="<%= header %>">
     31  <p><span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span>
     32  <%= text %>
     33  </p>
     34</div>
     35</script>       
     36
     37<script type="text/template" id="variationdialog_template">
     38<div class="variationDialog" title="Variate algorithm">
     39  <h1>Select parameter</h1>
     40  <select class="variationDialogContent"> 
     41  </select>
     42  <input type="checkbox" name="active" /> Active
     43  <div class="variationDetails">         
     44  </div> 
     45</div>
     46</script>       
     47
     48<script type="text/template" id="variationentry_template">
     49<option data-index='<%= Index %>'><%= Name %></option>
     50</script>       
     51
     52<script type="text/template" id="variationcontent_template">
     53<div>
     54 
     55 
     56</div>
     57</script>       
     58
     59<script type="text/template" id="variation_boolean_template">
     60<p>Boolean paramter: True / False</p>
     61</script>       
     62
     63<script type="text/template" id="variation_number_template">
     64<div>
     65    <input type="button" name="generate" value="Generate..."/>   
     66    <div></div>
     67</div>
     68</script>       
     69
     70<script type="text/template" id="checkbox_template">
     71<div>
     72    <input type="checkbox" name="<%=name%>"/><%=text%><br/>
     73</div>
     74</script>       
     75
     76<script type="text/template" id="variation_generator_template">
     77<div title="Generate Values">
     78 <div class="leftEntry">Minimum:</div>
     79 <div class="rightEntry"><input type="text" name="minimum" value="0"/></div> 
     80 <div class="leftEntry">Maximum:</div>
     81 <div class="rightEntry"><input type="text" name="maximum" value="2"/></div> 
     82 <div class="leftEntry">Step:</div>
     83 <div class="rightEntry"><input type="text" name="step" value="1"/></div> 
     84</div>
     85</script>       
     86
     87<script type="text/template" id="loading_template">
     88<div>
     89  <p>Loading ... </p>
     90  <img src="@Url.Content("~/Content/ajax-loader.gif")" alt="Loading animation" class="loader" /> 
     91</div>
     92</script>   
    693
    794<script type="text/javascript">
    8   function Experiment() {
    9     this.algorithms = [];
    10     this.nodeMapping = {};
    11     this.name = "My Experiment"
    12   }
    13    
    14   Experiment.prototype.buildAndStore = function(node, index, tree, ctx) {
    15     var result = this.build(node, index, tree, 'Experiment');
    16     this.algorithms = result.algorithms;
    17     this.nodeMapping = result.mapping;
    18   }
    19 
    20   Experiment.prototype.build = function(node, index, tree, ctx) {
    21     var stack = new Array();
    22     var root = {name : node.title, children: [], context: ctx};
    23     var nodeMapping = {};
    24     this.fetchNode(root, node, index, tree);
    25     if (node.title != 'Experiment')
    26       nodeMapping[node.key] = root;
    27      
    28     if (node.children)
    29         for (var i=0; i < node.children.length; i++) {
    30           stack.push({parent: root, child: node.children[node.children.length - 1 - i], index: node.children.length - 1 - i});
    31         }
    32     while(stack.length > 0) {
    33       var tmp = stack.pop();
    34       var parent = tmp.parent;
    35       var child = tmp.child;
    36       var newChild = { name : child.title, children: [], context: ctx}
    37       // fetch the nodes from the server
    38       this.fetchNode(newChild, child, tmp.index, tree);
    39       nodeMapping[tmp.child.key] = newChild;     
    40       parent.children.push(newChild);
    41       if (child.children)
    42           for (var i=0; i < child.children.length; i++) {
    43             stack.push({parent: newChild, child: child.children[child.children.length - 1 - i], index: child.children.length - 1 - i});
    44           }
    45     }
    46     return {algorithms: root, mapping: nodeMapping};
    47   }
    48 
    49   Experiment.prototype.fetchNode = function(modelNode, dynaNode, index, tree) {
    50     if (modelNode.name == 'Experiment')
    51       return;
    52     var self = this;
    53     var node = tree.getNodeByKey(dynaNode.key);
    54     $.ajax({
    55         type: "GET",
    56         url: '/Experiment/GetParameters',
    57         data: { scenario: modelNode.name, context: modelNode.context, index: index },
    58         contentType: "application/json; charset=utf-8",
    59         dataType: "json",
    60         success: function (result) {
    61             if (result.Type == "Complex") {
    62                 // extend the tree element
    63                 node.removeChildren();
    64                 var parent = self.nodeMapping[node.data.key];
    65                 for (var i=0; i < result.Subnames.length; i++) {
    66                     // add node to dynatree
    67                     var childNode = node.addChild({title: result.Subnames[i]});
    68                     var internalResult = self.build(childNode.toDict(true), i, tree, modelNode.name); 
    69                     parent.children.push(internalResult.algorithms);
    70                     for (var attrname in internalResult.mapping) { self.nodeMapping[attrname] = internalResult.mapping[attrname]; }                 
    71                 }
    72             } else if (result.Type == "Basic") {     
    73                 // replace the wizard   
    74                 previousWizards[node.data.key] = replaceWizard(result);
    75                 saveParameters(previousWizards[node.data.key], node);
    76             }
    77         }
     95    var controller = new ExperimentPageController();
     96    $(document).ready(function () {
     97        controller.create();
    7898    });
    79   }
    80 
    81   Experiment.prototype.pushNode = function(parentKey, nodeKey, entryName, ctx) {
    82     var entry = {name: entryName, children: [], context: ctx};
    83     this.nodeMapping[parentKey].children.push(entry);
    84     this.nodeMapping[nodeKey] = entry;
    85   }
    86 
    87   var experiment = new Experiment();
    88   var previousWizards = {};
    89 
    90   function saveExperiment() {
    91     $('.buttonFinish').attr('disabled', 'disabled');
    92     experiment["name"] = $('#name').val();
    93     experiment["run"] = $('#runImmediately').attr('checked') == 'checked';
    94     experiment["repititions"] = $('#repititions').val();
    95     experiment["group"] = $('#group').val();
    96 
    97      $.ajax({ type: "POST",
    98       url: '/Experiment/SaveExperiment',
    99       data: JSON.stringify(experiment),
    100       contentType: "application/json; charset=utf-8",
    101       dataType: "json",
    102       success: function (result) {
    103         $('#status-dialog').dialog("open");
    104       },
    105       error: function (result) {
    106       }
    107      });
    108   }
    109 
    110   function treeIndexOf(sibling) {
    111     var i = 0;
    112     var prev = sibling.getPrevSibling()
    113     while (prev != null) {
    114         i++;
    115         prev = prev.getPrevSibling()
    116     }
    117     return i;
    118   }
    119 
    120   function saveParameters(wiz, node) {
    121     var wiz = typeof wiz !== 'undefined' ? $(wiz) : $('.wizard', '#parameter-dialog-content');
    122     var id = wiz.attr('id');
    123     var node = typeof node !== 'undefined' ? node : $('#container2').dynatree("getActiveNode");
    124     var data = {};   
    125 
    126     for (var i = 1; i < 3; i++) {
    127       var stepId = '#' + id + '_' + i;
    128       var step = $(stepId);
    129       if (step.length == 0) {
    130         break;
    131       }
    132       var stepDesc = $('a[href="' + stepId + '"] span', wiz).contents()[0].data;
    133       var dataEntries = $('input, select', step);
    134       var entry = { };
    135       var mapper = new DatatypeMapper();
    136       for (var j = 0; j < dataEntries.length; j++) {
    137         entry[dataEntries[j].name] = mapper.mapString(dataEntries[j].value);
    138       }
    139       data[stepDesc] = entry;
    140     }
    141    
    142     // aggregate tables:
    143     var mapper = new DatatypeMapper();
    144     mapper.aggregateTables(data);
    145 
    146     var experimentEntry = experiment.nodeMapping[node.data.key];
    147     // we are at the node, update data
    148     experimentEntry["data"] = data;
    149     // Close dialog
    150     $('#params').dialog("close");
    151   }
    152 
    153   function createParamterDiv(name, parameters) {
    154     var mapper = new DatatypeMapper();
    155     // get algorithm parameters
    156     var paramsDiv = $('<div />').data("name", name);
    157     for (var i=0; i < parameters.length; i++) {
    158       var property = parameters[i];
    159       var content = mapper.mapHtml(property.Value);
    160 
    161       // add to canvas             
    162       $('<h2/>').text(property.Value.Name).appendTo(paramsDiv);
    163       content.appendTo(paramsDiv);
    164       $('<div />').addClass('clearer').appendTo(paramsDiv);
    165     }
    166     return paramsDiv;
    167   }
    168 
    169   function createWizard(name, steps) {
    170     var wizard = $('<div />', { id: name }).addClass('wizard swMain');
    171     var stepMenu = $('<ul />');
    172     var prefix = name + '_';
    173     for (var i = 0; i < steps.length; i++) {
    174       var step = steps[i];
    175       var a = $('<a></a>', {href: '#' + prefix + (i + 1)});
    176       $('<label />').addClass("stepNumber").text((i + 1)).appendTo(a);
    177       $('<span />').addClass("stepDesc").html(step.heading + '<br /><small>' + step.description + '</small>').appendTo(a);
    178       var li = $('<li />').append(a);
    179       li.appendTo(stepMenu);
    180     }
    181     stepMenu.appendTo(wizard);
    182     for (var i = 0; i < steps.length; i++) {
    183       var div = $('<div />', { id: prefix + (i + 1) });
    184       if (steps[i].content && steps[i].content != null)
    185         div.append(steps[i].content);
    186       div.appendTo(wizard);
    187     }
    188     return wizard;
    189   }
    190 
    191 
    192   function makeTree() {
    193     var tree = $('#container').dynatree({
    194       onActivate: function (node) {
    195         if (node && node.data.title !== "Experiment") {
    196           $('input[name="RemoveNode"]').removeAttr("disabled");
    197         } else if (node) {
    198           $('input[name="RemoveNode"]').attr("disabled", "disabled");
    199         }
    200       },
    201       onDeactivate: function (node) {
    202       },
    203       dnd: {
    204         autoExpandMS: 750,
    205 
    206         onDragStart: function (node) {
    207           return node.data.title !== "Experiment";
    208         },
    209         onDragEnter: function (node, sourceNode) {
    210           return true;
    211         },
    212         onDragOver: function (node, sourceNode, hitMode) {
    213           return node.data.title !== "Experiment" || hitMode === "over";
    214         },
    215         onDrop: function (node, sourceNode, hitMode, ui, draggable) {
    216           if (sourceNode) {
    217             sourceNode.move(node, hitMode);
    218           }
    219           else {
    220             newNode = { title: draggable.element[0].id };
    221             if (hitMode == "over") {
    222               node.addChild(newNode);
    223               node.expand(true);
    224             }
    225             else if (hitMode == "before") {
    226               node.parent.addChild(newNode, node);
    227             }
    228             else {
    229               node.parent.addChild(newNode, node.getNextSibling());
    230             }
    231           }
    232         },
    233         onDragLeave: function (node, sourceNode) {
    234         }
    235       }
    236     });
    237 
    238     $('.dragables').each(function () {
    239       $(this).draggable({
    240         revert: true,
    241         connectToDynatree: true,
    242         cursorAt: { top: -5, left: -5 },
    243         helper: "clone"
    244       });
    245     });
    246 
    247     $('input[name="RemoveNode"]').click(function () {
    248       var node = $("#container").dynatree("getActiveNode");
    249       if (node && node.data.title !== "Experiment")
    250         node.remove();
    251       $(this).attr("disabled", "disabled");
    252     });
    253   }
    254 
    255   function leaveStep(obj) {
    256     var stepNum = obj.attr("rel");
    257     return validateStep(stepNum);
    258   }
    259 
    260   function validateStep(stepNum) {
    261     var isStepValid = true;
    262     if (stepNum == 1) {
    263       previousWizards = {}
    264       experiment = new Experiment();
    265       var data = $("#container").dynatree("getTree").toDict().children;
    266       $("#container2").dynatree({
    267         onActivate: editElement
    268       });
    269       var rootNode = $("#container2").dynatree("getRoot");
    270       rootNode.removeChildren();
    271       rootNode.addChild(data);
    272       // based on the data rebuild the experiment
    273       experiment.buildAndStore(data[0], 0, $("#container2").dynatree("getTree"));
    274     }
    275     return isStepValid;
    276   }
    277 
    278   function resetDialog() {
    279     var canvas = $('#parameter-dialog-content');
    280     canvas.empty();
    281     $('<img />').attr('alt', 'Loading animation').attr('src', '@Url.Content("~/Content/ajax-loader.gif")').attr('class', 'loader').appendTo(canvas);
    282     $('<div />').text("Loading...").appendTo(canvas);       
    283   }
    284 
    285   globalCounter = 0;
    286 
    287   function replaceWizard(result) {
    288     var canvas = $('#parameter-dialog-content');
    289     canvas.empty();
    290 
    291     // get parameters as div
    292     var algoParamsDiv = null;
    293 
    294     if (result.Algorithm.Parameters) {
    295         algoParamsDiv = createParamterDiv("Algorithm Parameters", result.Algorithm.Parameters.Items);
    296     }
    297 
    298     var problemParamsDiv = null;
    299     if (result.Algorithm.Problem && result.Algorithm.Problem.Parameters) {
    300      problemParamsDiv = createParamterDiv("Problem Parameters", result.Algorithm.Problem.Parameters.Items);
    301     }
    302 
    303     var wizard = null;
    304     if (result.Algorithm.Problem)
    305      wizard = createWizard("TestWizard", [
    306         { heading: "Algorithm Parameters", description: "Adjust algorithm parameters", content: algoParamsDiv },
    307         { heading: "Problem Parameters", description: "Adjust problem parameters", content: problemParamsDiv }
    308     ]);
    309     else
    310      wizard = createWizard("TestWizard", [
    311         { heading: "Algorithm Parameters", description: "Adjust algorithm parameters", content: algoParamsDiv }
    312     ]);
    313 
    314     wizard.appendTo(canvas);
    315     $(".wizard", canvas).smartWizard({
    316         onFinish: saveParameters,
    317         labelFinish: 'Save'
    318     });
    319     return wizard;
    320   }
    321 
    322   function editElement(node) {
    323     resetDialog();
    324     $("#params").dialog("open");
    325     // if we opened this windows before, use the previously created wizard
    326     if (node.data.key in previousWizards) {
    327       var canvas = $('#parameter-dialog-content');
    328       canvas.empty(); 
    329       $(previousWizards[node.data.key]).appendTo(canvas);
    330       var wiz = $(".wizard", canvas).smartWizard({
    331         onFinish: saveParameters,
    332         labelFinish: 'Save'
    333       });
    334       // we have to recreate the wizard, otherwise it is not responsive -> remove some multiple occuring wizard elements.
    335       var parent = $('.stepContainer.content', wiz).parent('.stepContainer:not(.content)');
    336       var elem = $('.stepContainer.content .content', wiz).detach();
    337       elem.appendTo(parent);
    338       $('.stepContainer.content', wiz).detach();
    339       $('.actionBar.content', wiz).detach();
    340     }
    341     else {
    342         $.ajax({
    343           type: "GET",
    344           url: '/Experiment/GetParameters',
    345           data: { scenario: node.data.title, context: experiment.nodeMapping[node.data.key].context, index: treeIndexOf(node) },
    346           contentType: "application/json; charset=utf-8",
    347           dataType: "json",
    348           success: function (result) {
    349             if (result.Type == "Complex") $("#params").dialog("close");
    350             /*if (result.Type == "Complex") {
    351               // extend the tree element     
    352               $("#params").dialog("close");     
    353               node.removeChildren();
    354               for (var i=0; i < result.Subnames.length; i++) {
    355                 // add node to dynatree
    356                 var childNode = node.addChild({title: result.Subnames[i]});
    357                 // add node to model
    358                 experiment.pushNode(node.data.key, childNode.data.key, result.Subnames[i], node.data.title);
    359               }
    360             } else*/
    361             if (result.Type == "Basic") {     
    362               // replace the wizard   
    363               previousWizards[node.data.key] = replaceWizard(result);
    364               saveParameters(previousWizards[node.data.key], node);
    365             }
    366           }
    367         });
    368      }
    369   }
    370 
    371   $(document).ready(function () {
    372     var wiz = $(".wizard").smartWizard({
    373       /*updateHeight: false*/
    374       onLeaveStep: leaveStep,
    375       onFinish: saveExperiment
    376     });
    377     makeTree();
    378 
    379     $("#params").dialog({
    380       autoOpen: false,
    381       width: 1024,
    382       height: 768,
    383       /*modal: true,
    384       buttons: {
    385         "Save parameters": function () {
    386          
    387         }
    388         ,
    389         "Cancel": function () {
    390           $(this).dialog("close");
    391         }
    392       },
    393       close: function () {
    394       }*/
    395     });
    396 
    397     $("#status-dialog").dialog({
    398       autoOpen: false,
    399       resizable: false,
    400       height: 100,
    401       modal: true,
    402       buttons: { "OK" : function() { $(this).dialog('close'); $('.buttonFinish').removeAttr('disabled'); } }
    403     });
    404 
    405     $('#runImmediately').change(
    406         function() {
    407             if ($(this).is(':checked')) {
    408                 $('#repititions').removeAttr('disabled');
    409                 $('#group').removeAttr('disabled');
    410             }
    411             else {
    412                 $('#repititions').attr('disabled', 'disabled');
    413                 $('#group').attr('disabled', 'disabled');
    414             }
    415         });
    416   });
    417 </script>
     99</script>
     100<noscript>
     101    <p>You need JavaScript to view this page! Please activate it in your browser settings.</p>
     102</noscript>
    418103
    419104<h2>Experiment</h2>
    420105
    421 <div class="wizard swMain">
     106<div id="stepWizard" class="wizard swMain">
    422107  <ul>
    423108    <li>
     
    450135  </ul>
    451136  <div id="step1">
    452   @using (Html.BeginForm("TreeData", "Tree"))
    453   {
    454137  <fieldset>   
    455138    <div>
    456139    <p>Experiment Tree:</p>
    457140    </div>
    458 
    459     <div id="container" class="treeStyle">
    460       <ul>
    461         <li id="root">Experiment</li>
    462       </ul>
    463     </div>
    464     <input style="margin-top:5px;"  name="RemoveNode" type="button" value="Remove" disabled="disabled" />
    465 
    466    
    467      @if (Model.Scenarios.Count > 0) {
    468         <p>Choose an algorithm:</p>
    469         foreach (var scen in Model.Scenarios) {
    470             <div class="dragables" id="@scen"><p>@scen</p></div>
    471         }       
    472         <div class="clearer"/>   
    473      }
    474    
    475     @if (Model.Scenarios.Count > 0) {
    476         <p>Choose from your stored experiments:</p>
    477         foreach (var scen in Model.Experiments) {
    478             <div class="dragables" id="@scen"><p>@scen</p></div>
    479         }
    480         <div class="clearer"/>
    481     }   
    482    
     141    <div id="container" class="treeStyle"></div>   
     142    <p>Choose an algorithm:</p>
     143    <div id="algorithms"></div>
     144    <div class="clearer"></div>
     145    <p>Choose from your stored experiments:</p>
     146    <div id="experiments"></div>
    483147  </fieldset>
    484   }
    485148  </div>
    486149  <div id="step2">
    487   <h2>Click on a experiment to adjust its parameters:</h2>
    488   <div id="container2" class="treeStyle">
    489       <ul>
    490         <li>Experiment</li>
    491       </ul>
    492     </div>
     150    <h2>Click on a experiment to adjust its parameters:</h2>
     151    <div id="container2" class="treeStyle"></div>
    493152  </div>
    494153  <div id="step3">
     
    524183      <input id="group" name="Group" type="text" value="TESTAZURE" disabled="disabled" />
    525184    </div>
    526   </div> 
    527 </div>
    528 
    529 <div id="status-dialog">
    530     <div>
    531       Experiment has been saved!
    532     </div>           
    533 </div>
    534 
    535 <div id="params" title="Update parameters">
    536     <!-- Note: The content must be loaded asynchronously -->
    537     <div id="parameter-dialog-content">
    538       <img src="@Url.Content("~/Content/ajax-loader.gif")" alt="Loading animation" class="loader" />
    539       Loading ...     
    540     </div>
    541            
    542   </div>
     185  </div>   
     186</div>
     187
     188<div id="parameterDialog">
     189  <div id="parameterDialog-content">
     190  </div>
     191</div>
     192
     193<div id="loadingDialog">
     194</div>
     195
     196@section submenu {
     197    <ul>
     198        <li class="selected">@Html.ActionLink("Build", "New")</li>   
     199        <li>@Html.ActionLink("Edit", "NewEdit")</li>
     200        <li>@Html.ActionLink("Status", "Index", "Status")</li>
     201    </ul>
     202}
  • branches/OaaS/HeuristicLab.Services.Optimization.Web/Views/Shared/_Layout.cshtml

    r9227 r9305  
    3535    <link href="@Url.Content("~/Content/smartwizard2.0/styles/smart_wizard.css")" rel="stylesheet" type="text/css" />
    3636    <script type="text/javascript" src="@Url.Content("~/Content/smartwizard2.0/js/jquery.smartWizard-2.0.min.js")"></script>
     37
     38    <script type='text/javascript' src='@Url.Content("~/Content/backbone/underscore.js")'></script>
     39    <script type='text/javascript' src='@Url.Content("~/Content/backbone/backbone-min.js")'></script>
     40    <script type='text/javascript' src='@Url.Content("~/Content/backbone/backbone-relational.js")'></script>
     41
     42    <script type='text/javascript' src='@Url.Content("~/Content/experiment.model.js")'></script>
     43    <script type='text/javascript' src='@Url.Content("~/Content/experiment.view.js")'></script>
     44    <script type='text/javascript' src='@Url.Content("~/Content/experiment.controller.js")'></script>
    3745</head>
    3846<body>
  • branches/OaaS/HeuristicLab.Services.Optimization.Web/packages.config

    r8384 r9305  
    1111  <package id="System.Web.Providers.Core" version="1.0" />
    1212  <package id="System.Web.Providers" version="1.1" />
     13  <package id="Newtonsoft.Json" version="4.5.11" />
    1314</packages>
Note: See TracChangeset for help on using the changeset viewer.