Changeset 17379
- Timestamp:
- 12/17/19 17:16:03 (5 years ago)
- Location:
- branches/3026_IntegrationIntoSymSpace
- Files:
-
- 5 deleted
- 16 edited
Legend:
- Unmodified
- Added
- Removed
-
branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/Constants.cs
r17353 r17379 14 14 internal const string Algorithm = "Algorithm"; 15 15 internal const string Problem = "Problem"; 16 internal const string Objects = "Objects"; 17 internal const string Types = "Types"; 18 internal const string StaticParameters = "StaticParameters"; 19 internal const string FreeParameters = "FreeParameters"; 16 internal const string HLFileLocation = "HLFileLocation"; 17 internal const string Parameters = "Parameters"; 20 18 21 19 internal const string Template = @"{ 22 'Metadata': { 23 'Algorithm':'', 24 'Problem':'' 20 '" + Metadata + @"': { 21 '" + Algorithm + @"':'', 22 '" + Problem + @"':'', 23 '" + HLFileLocation + @"':'' 25 24 }, 26 'Objects': [], 27 'Types': {} 25 '" + Parameters + @"': [] 28 26 }"; 29 27 } -
branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/Converters/BaseConverter.cs
r17374 r17379 12 12 { 13 13 public void Inject(IItem item, JsonItem data) { 14 if (data.Reference != null) {15 JsonItem.Merge(data, data.Reference);16 }17 14 InjectData(item, data); 18 15 } … … 21 18 JsonItem data = ExtractData(value); 22 19 data.Name = string.IsNullOrEmpty(data.Name) ? value.ItemName : data.Name; 23 data.Type = string.IsNullOrEmpty(data.Type) ? value.GetType().AssemblyQualifiedName : data.Type;24 20 return data; 25 21 } … … 31 27 protected ValueType CastValue<ValueType>(object obj) { 32 28 if (obj is JToken) 33 return (obj.Cast<JToken>()).ToObject<ValueType>();29 return obj.Cast<JToken>().ToObject<ValueType>(); 34 30 else if (obj is IConvertible) 35 31 return Convert.ChangeType(obj, typeof(ValueType)).Cast<ValueType>(); … … 49 45 50 46 switch (typeCode) { 51 case TypeCode.Int16: return Int16.MaxValue;52 case TypeCode.Int32: return Int32.MaxValue;53 case TypeCode.Int64: return Int64.MaxValue;54 case TypeCode.UInt16: return UInt16.MaxValue;55 case TypeCode.UInt32: return UInt32.MaxValue;56 case TypeCode.UInt64: return UInt64.MaxValue;57 case TypeCode.Single: return Single.MaxValue;58 case TypeCode.Double: return Double.MaxValue;59 case TypeCode.Decimal: return Decimal.MaxValue;60 case TypeCode.Byte: return Byte.MaxValue;47 case TypeCode.Int16: return short.MaxValue; 48 case TypeCode.Int32: return int.MaxValue; 49 case TypeCode.Int64: return long.MaxValue; 50 case TypeCode.UInt16: return ushort.MaxValue; 51 case TypeCode.UInt32: return uint.MaxValue; 52 case TypeCode.UInt64: return ulong.MaxValue; 53 case TypeCode.Single: return float.MaxValue; 54 case TypeCode.Double: return double.MaxValue; 55 case TypeCode.Decimal: return decimal.MaxValue; 56 case TypeCode.Byte: return byte.MaxValue; 61 57 case TypeCode.Boolean: return true; 62 58 default: return GetDefaultValue(t); … … 71 67 72 68 switch (typeCode) { 73 case TypeCode.Int16: return Int16.MinValue;74 case TypeCode.Int32: return Int32.MinValue;75 case TypeCode.Int64: return Int64.MinValue;76 case TypeCode.UInt16: return UInt16.MinValue;77 case TypeCode.UInt32: return UInt32.MinValue;78 case TypeCode.UInt64: return UInt64.MinValue;79 case TypeCode.Single: return Single.MinValue;80 case TypeCode.Double: return Double.MinValue;81 case TypeCode.Decimal: return Decimal.MinValue;82 case TypeCode.Byte: return Byte.MinValue;69 case TypeCode.Int16: return short.MinValue; 70 case TypeCode.Int32: return int.MinValue; 71 case TypeCode.Int64: return long.MinValue; 72 case TypeCode.UInt16: return ushort.MinValue; 73 case TypeCode.UInt32: return uint.MinValue; 74 case TypeCode.UInt64: return ulong.MinValue; 75 case TypeCode.Single: return float.MinValue; 76 case TypeCode.Double: return double.MinValue; 77 case TypeCode.Decimal: return decimal.MinValue; 78 case TypeCode.Byte: return byte.MinValue; 83 79 case TypeCode.Boolean: return false; 84 80 default: return GetDefaultValue(t); … … 87 83 88 84 protected object GetDefaultValue(Type t) => t.IsValueType ? Activator.CreateInstance(t) : null; 89 90 85 #endregion 91 86 } -
branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/Converters/ConstrainedValueParameterConverter.cs
r17353 r17379 14 14 parameter.ActualValue = x; 15 15 16 if (parameter.ActualValue is IParameterizedItem && data.Reference != null) 17 JsonItemConverter.Inject(parameter.ActualValue, data.Reference); 16 if (parameter.ActualValue is IParameterizedItem && data.Children != null) { 17 foreach(var param in data.Children) { 18 if(param.Name == parameter.ActualValue.ItemName) 19 JsonItemConverter.Inject(parameter.ActualValue, param); 20 } 21 } 18 22 } 19 23 … … 23 27 Value = value.ActualValue?.ToString(), 24 28 Range = GetValidValues(value).Select(x => x.ToString()), 25 Parameters= GetParameterizedChilds(value)29 Children = GetParameterizedChilds(value) 26 30 }; 27 31 -
branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/Converters/MultiCheckedOperatorConverter.cs
r17374 r17379 12 12 JsonItem data = base.ExtractData(value); 13 13 14 if(data. Parameters== null)15 data. Parameters= new List<JsonItem>();14 if(data.Children == null) 15 data.Children = new List<JsonItem>(); 16 16 dynamic val = value.Cast<dynamic>(); 17 17 foreach (var op in val.Operators) { 18 data. Parameters.Add(new JsonItem() {18 data.Children.Add(new JsonItem() { 19 19 Name = op.Name, 20 20 Value = val.Operators.ItemChecked(op), 21 Range = new object[] { false, true }/*, 22 Path = data.Path + "." + op.Name*/ 21 Range = new object[] { false, true } 23 22 }); 24 23 } … … 35 34 36 35 private bool GetOperatorState(string name, JsonItem data) { 37 foreach(var op in data. Operators) {38 if (op.Name == name ) return op.Value.Cast<bool>();36 foreach(var op in data.Children) { 37 if (op.Name == name && op.Value is bool) return op.Value.Cast<bool>(); 39 38 } 40 39 return false; -
branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/Converters/ParameterBaseConverter.cs
r17374 r17379 8 8 namespace HeuristicLab.JsonInterface { 9 9 public abstract class ParameterBaseConverter : BaseConverter { 10 public override JsonItem ExtractData(IItem value) { 11 IParameter param = value.Cast<IParameter>(); 12 JsonItem comp = ExtractData(param); 13 return comp; 14 } 10 public override JsonItem ExtractData(IItem value) => 11 ExtractData(value.Cast<IParameter>()); 12 15 13 public abstract JsonItem ExtractData(IParameter value); 16 14 -
branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/Converters/ParameterizedItemConverter.cs
r17374 r17379 11 11 IParameterizedItem pItem = item.Cast<IParameterizedItem>(); 12 12 13 if(data. Parameters!= null) {14 foreach (var sp in data. Parameters)13 if(data.Children != null) { 14 foreach (var sp in data.Children) 15 15 if (pItem.Parameters.TryGetValue(sp.Name, out IParameter param)) 16 16 JsonItemConverter.Inject(param, sp); … … 27 27 //data.Name = param.Name; 28 28 29 if (item. Parameters== null)30 item. Parameters= new List<JsonItem>();31 item. Parameters.Add(data);29 if (item.Children == null) 30 item.Children = new List<JsonItem>(); 31 item.Children.Add(data); 32 32 } 33 33 } -
branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/Converters/RegressionProblemDataConverter.cs
r17375 r17379 14 14 JsonItem item = new JsonItem() { 15 15 Path = value.ItemName, 16 Parameters= new List<JsonItem>()16 Children = new List<JsonItem>() 17 17 }; 18 19 Type type = value.GetType(); 20 18 21 19 dynamic val = (dynamic)value; 22 20 object dataset = (object)val.Dataset; … … 24 22 FieldInfo dataInfo = dataset.GetType().GetField("storableData", flags); 25 23 // TODO: aufteilen in trainings und test daten abschnitte 26 item. Parameters.Add(new JsonItem() {24 item.Children.Add(new JsonItem() { 27 25 Name = "Dataset", 28 26 Value = dataInfo.GetValue(dataset), … … 31 29 32 30 IEnumerable<StringValue> variables = (IEnumerable<StringValue>)val.InputVariables; 33 item. Parameters.Add(new JsonItem() {31 item.Children.Add(new JsonItem() { 34 32 Name = "TargetVariable", 35 33 Value = (object)targetVariable, … … 39 37 40 38 41 item. Parameters.Add(new JsonItem() {39 item.Children.Add(new JsonItem() { 42 40 Name = "AllowedInputVariables", 43 41 Value = (object)val.AllowedInputVariables, … … 46 44 }); 47 45 48 /*49 item.Parameters.Add(new JsonItem() {50 Name = "InputVariables",51 Value = variables.Select(x => x.Value),52 Path = "InputVariables"53 });54 */55 46 item.UpdatePath(); 56 47 … … 59 50 60 51 public override void InjectData(IItem item, JsonItem data) { 52 // TODO: inject data 61 53 throw new NotImplementedException(); 62 54 } -
branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/Converters/ValueLookupParameterConverter.cs
r17353 r17379 16 16 actualValue = tmp.Value; 17 17 actualRange = tmp.Range; 18 } else { 19 actualRange = new object[] { GetMinValue(param.DataType), GetMaxValue(param.DataType) }; 18 20 } 21 19 22 return new JsonItem() { 20 23 Name = value.Name, -
branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/Converters/ValueRangeConverter.cs
r17374 r17379 19 19 where TType : struct { 20 20 21 private const BindingFlags Flags = BindingFlags.NonPublic | BindingFlags.Instance; 22 21 23 public override JsonItem ExtractData(IItem value) { 22 var field = value.GetType().GetField("values", BindingFlags.NonPublic | BindingFlags.Instance);24 var field = value.GetType().GetField("values", Flags); 23 25 Tuple<T,T> tuple = (Tuple<T,T>)field.GetValue(value); 24 26 … … 34 36 object[] arr = (object[])data.Value; 35 37 Tuple<T,T> tuple = new Tuple<T,T>(Instantiate<T>(arr[0]), Instantiate<T>(arr[1])); 36 var field = item.GetType().GetField("values", BindingFlags.NonPublic | BindingFlags.Instance);38 var field = item.GetType().GetField("values", Flags); 37 39 field.SetValue(tuple, item); 38 40 } -
branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/Converters/ValueTypeMatrixConverter.cs
r17374 r17379 14 14 { 15 15 public override void InjectData(IItem item, JsonItem data) => 16 CopyMatrixData(item.Cast<MatrixType>(), CastValue<T[,]>(data.Value));16 CopyMatrixData(item.Cast<MatrixType>(), data.Value); 17 17 18 18 public override JsonItem ExtractData(IItem value) => … … 23 23 24 24 #region Helper 25 private void CopyMatrixData(MatrixType matrix, T[,] data) { 26 var rowInfo = matrix.GetType().GetProperty("Rows"); 27 rowInfo.SetValue(matrix, data.GetLength(0)); 28 var colInfo = matrix.GetType().GetProperty("Columns"); 29 colInfo.SetValue(matrix, data.GetLength(1)); 25 private void CopyMatrixData(MatrixType matrix, object data) { 26 if (data is Array arr) { 27 var rows = arr.Length; 28 var cols = arr.Length > 0 && arr.GetValue(0) is JArray jarr ? jarr.Count : 0; 30 29 31 for (int x = 0; x < data.GetLength(0); ++x) { 32 for (int y = 0; y < data.GetLength(1); ++y) { 33 matrix[x, y] = data[x, y]; 30 var rowInfo = matrix.GetType().GetProperty("Rows"); 31 rowInfo.SetValue(matrix, rows); 32 var colInfo = matrix.GetType().GetProperty("Columns"); 33 colInfo.SetValue(matrix, cols); 34 35 for (int x = 0; x < rows; ++x) { 36 jarr = (JArray)arr.GetValue(x); 37 for (int y = 0; y < cols; ++y) { 38 matrix[x, y] = jarr[y].ToObject<T>(); 39 } 34 40 } 35 41 } -
branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/HeuristicLab.JsonInterface.csproj
r17374 r17379 63 63 <Compile Include="Attributes\ConvertableAttribute.cs" /> 64 64 <Compile Include="Constants.cs" /> 65 <Compile Include="Converters\CheckedItemListConverter.cs" />66 <Compile Include="Converters\ConfigurableConverter.cs" />67 <Compile Include="Converters\ItemCollectionConverter.cs" />68 <Compile Include="Converters\PrimitiveConverter.cs" />69 65 <Compile Include="Converters\RegressionProblemDataConverter.cs" /> 70 <Compile Include="Converters\StorableConverter.cs" />71 66 <Compile Include="Converters\ValueLookupParameterConverter.cs" /> 72 67 <Compile Include="Converters\ValueRangeConverter.cs" /> -
branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/JCGenerator.cs
r17374 r17379 17 17 private struct GenData { 18 18 public JObject Template { get; set; } 19 public IDictionary<string, string> TypeList { get; set; }20 19 public JArray JsonItems { get; set; } 21 20 } … … 25 24 GenData genData = new GenData() { 26 25 Template = JObject.Parse(Constants.Template), 27 TypeList = new Dictionary<string, string>(),28 26 JsonItems = new JArray() 29 27 }; … … 31 29 ProtoBufSerializer serializer = new ProtoBufSerializer(); 32 30 serializer.Serialize(algorithm, @"C:\Workspace\template.hl"); 33 31 genData.Template[Constants.Metadata][Constants.HLFileLocation] = @"C:\Workspace\template.hl"; 34 32 35 // 1.1.extract JsonItem, save the name in the metadata section of the33 // extract JsonItem, save the name in the metadata section of the 36 34 // template and save it an JArray incl. all parameters of the JsonItem, 37 35 // which have parameters aswell 38 36 AddInstantiableIItem(Constants.Algorithm, algorithm, genData); 39 37 //IsConvertable(algorithm, true); 40 if (algorithm.Problem != null) // 1.2.only when an problem exists38 if (algorithm.Problem != null) // only when an problem exists 41 39 AddInstantiableIItem(Constants.Problem, algorithm.Problem, genData); 42 40 43 // 2. save the JArray with JsonItems (= IParameterizedItems) 44 genData.Template[Constants.Objects] = genData.JsonItems; 45 // 3. save the types of the JsonItems (for instatiation) 46 genData.Template[Constants.Types] = JObject.FromObject(genData.TypeList); 47 // 4. serialize template and return string 41 // save the JArray with JsonItems (= IParameterizedItems) 42 genData.Template[Constants.Parameters] = genData.JsonItems; 43 // serialize template and return string 48 44 return CustomJsonWriter.Serialize(genData.Template); 49 45 } … … 65 61 // serializes ParameterizedItems and saves them in list "JsonItems". 66 62 private static void PopulateJsonItems(JsonItem item, GenData genData) { 67 if (item.Parameters != null) { 68 foreach (var p in item.Parameters) { 63 IEnumerable<JsonItem> tmpParameter = item.Children; 64 item.Children = null; 65 66 if (item.Value != null || item.Range != null) { 67 genData.JsonItems.Add(Serialize(item)); 68 } 69 70 if (tmpParameter != null) { 71 foreach (var p in tmpParameter) { 69 72 PopulateJsonItems(p, genData); 70 73 } 71 }else if (item.Value != null || item.Range != null /*|| item.ActualName != null*/) {72 genData.JsonItems.Add(Serialize(item, genData));73 74 } 74 /*75 if (item.Parameters != null) {76 if (item.Range == null)77 genData.JsonItems.Add(Serialize(item, genData));78 foreach (var p in item.Parameters)79 if (p.IsParameterizedItem)80 PopulateJsonItems(p, genData);81 }*/82 75 } 83 76 84 private static JObject Serialize(JsonItem item, GenData genData) { 85 JObject obj = JObject.FromObject(item, Settings()); 86 //obj[Constants.StaticParameters] = obj[nameof(JsonItem.Parameters)]; 87 //obj[Constants.FreeParameters] = obj[nameof(JsonItem.Parameters)]; 88 89 //obj.Property(nameof(JsonItem.Parameters))?.Remove(); 90 //RefactorFreeParameters(obj, genData); 91 //RefactorStaticParameters(obj, genData); 92 93 //obj.Property(nameof(JsonItem.Value))?.Remove(); 94 obj.Property(nameof(JsonItem.Type))?.Remove(); 95 96 if(!genData.TypeList.ContainsKey(item.Path)) 97 genData.TypeList.Add(item.Path, item.Type); 98 return obj; 99 } 100 101 // deletes unnecessary properties for free parameters. 102 private static void RefactorFreeParameters(JToken token, GenData genData) { 103 IList<JObject> objToRemove = new List<JObject>(); 104 TransformNodes(x => { 105 var p = JsonItem.BuildJsonItem(x, genData.TypeList); 106 x.Property(nameof(JsonItem.Type))?.Remove(); 107 x.Property(nameof(JsonItem.Parameters))?.Remove(); 108 /* 109 if ((p.Value == null || (p.Value != null && p.Value.GetType() == typeof(string) && p.Range == null) && p.ActualName == null)) { 110 objToRemove.Add(x); 111 } else { 112 x.Property(nameof(JsonItem.Type))?.Remove(); 113 x.Property(nameof(JsonItem.Parameters))?.Remove(); 114 }*/ 115 }, token[Constants.FreeParameters]); 116 //foreach (var x in objToRemove) x.Remove(); 117 } 118 119 // deletes unnecessary properties for static parameters. 120 private static void RefactorStaticParameters(JToken token, GenData genData) { 121 IList<JObject> objToRemove = new List<JObject>(); 122 TransformNodes(x => { 123 var p = JsonItem.BuildJsonItem(x, genData.TypeList); 124 x.Property(nameof(JsonItem.Range))?.Remove(); 125 x.Property(nameof(JsonItem.Operators))?.Remove(); 126 x.Property(nameof(JsonItem.Parameters))?.Remove(); 127 x.Property(nameof(JsonItem.Type))?.Remove(); 128 //TODO: maybe allow JsonItems with Value==null in static parameters too? 129 if (p.Value == null) objToRemove.Add(x); 130 }, token[Constants.StaticParameters]); 131 //foreach (var x in objToRemove) x.Remove(); 132 } 77 private static JObject Serialize(JsonItem item) => 78 JObject.FromObject(item, Settings()); 133 79 134 80 /// <summary> … … 141 87 ReferenceLoopHandling = ReferenceLoopHandling.Serialize 142 88 }; 143 144 private static void TransformNodes(Action<JObject> action, params JToken[] tokens) {145 foreach(JObject obj in tokens.SelectMany(x => x.Children<JObject>()))146 action(obj);147 }148 89 #endregion 149 90 } -
branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/JCInstantiator.cs
r17354 r17379 7 7 using System.Text; 8 8 using System.Threading.Tasks; 9 using HEAL.Attic; 9 10 using HeuristicLab.Core; 10 11 using HeuristicLab.Data; … … 21 22 public JToken Template { get; set; } 22 23 public JArray Config { get; set; } 23 public Dictionary<string, string> TypeList { get; set; } 24 public IDictionary<string, JsonItem> ParameterizedItems { get; set; } 25 public IDictionary<string, JsonItem> ConfigurableItems { get; set; } 24 public IDictionary<string, JsonItem> Objects { get; set; } 25 public IDictionary<string, JsonItem> ResolvedItems { get; set; } 26 26 } 27 27 … … 34 34 public static IAlgorithm Instantiate(string templateFile, string configFile = "") { 35 35 InstData instData = new InstData() { 36 TypeList = new Dictionary<string, string>(), 37 ParameterizedItems = new Dictionary<string, JsonItem>(), 38 ConfigurableItems = new Dictionary<string, JsonItem>() 36 Objects = new Dictionary<string, JsonItem>(), 37 ResolvedItems = new Dictionary<string, JsonItem>() 39 38 }; 40 39 41 // 1. Parse Template and Config files40 // parse template and config files 42 41 instData.Template = JToken.Parse(File.ReadAllText(templateFile)); 43 42 if(!string.IsNullOrEmpty(configFile)) 44 43 instData.Config = JArray.Parse(File.ReadAllText(configFile)); 45 instData.TypeList = instData.Template[Constants.Types].ToObject<Dictionary<string, string>>(); 44 45 // extract metadata information 46 46 string algorithmName = instData.Template[Constants.Metadata][Constants.Algorithm].ToString(); 47 47 string problemName = instData.Template[Constants.Metadata][Constants.Problem].ToString(); 48 string hLFileLocation = instData.Template[Constants.Metadata][Constants.HLFileLocation].ToString(); 48 49 49 //2. Collect all parameterizedItems from template 50 // deserialize hl file 51 ProtoBufSerializer serializer = new ProtoBufSerializer(); 52 IAlgorithm algorithm = (IAlgorithm)serializer.Deserialize(hLFileLocation); 53 54 // collect all parameterizedItems from template 50 55 CollectParameterizedItems(instData); 51 56 52 // 3. select all ConfigurableItems53 SelectConfigurableItems(instData);57 // rebuild tree with paths 58 RebuildTree(instData); 54 59 55 // 4.if config != null -> merge Template and Config60 // if config != null -> merge Template and Config 56 61 if (instData.Config != null) 57 62 MergeTemplateWithConfig(instData); 58 63 59 // 5. resolve the references between parameterizedItems60 ResolveReferences(instData);64 // get algorthm data and object 65 JsonItem algorithmData = GetData(algorithmName, instData); 61 66 62 //6. get algorthm data and object 63 JsonItem algorithmData = GetData(algorithmName, instData); 64 IAlgorithm algorithm = CreateObject<IAlgorithm>(algorithmData, instData); 67 // get problem data and object 68 JsonItem problemData = GetData(problemName, instData); 65 69 66 //7. get problem data and object 67 JsonItem problemData = GetData(problemName, instData); 68 IProblem problem = CreateObject<IProblem>(problemData, instData); 69 algorithm.Problem = problem; 70 71 //8. inject configuration 70 // inject configuration 72 71 JsonItemConverter.Inject(algorithm, algorithmData); 73 JsonItemConverter.Inject(problem, problemData); 74 75 // TODO: let the engine be configurable 76 if (algorithm is EngineAlgorithm) 77 algorithm.Cast<EngineAlgorithm>().Engine = new SequentialEngine.SequentialEngine(); 72 if(algorithm.Problem != null) 73 JsonItemConverter.Inject(algorithm.Problem, problemData); 78 74 79 75 return algorithm; … … 82 78 #region Helper 83 79 private static void CollectParameterizedItems(InstData instData) { 84 foreach (JObject item in instData.Template[Constants. Objects]) {85 JsonItem data = JsonItem.BuildJsonItem(item , instData.TypeList);86 instData. ParameterizedItems.Add(data.Path, data);80 foreach (JObject item in instData.Template[Constants.Parameters]) { 81 JsonItem data = JsonItem.BuildJsonItem(item); 82 instData.Objects.Add(data.Path, data); 87 83 } 88 84 } 85 86 private static JsonItem RebuildTreeHelper(IList<JsonItem> col, string name) { 87 JsonItem target = null; 88 foreach (var val in col) { 89 if (val.Name == name) 90 target = val; 91 } 92 if (target == null) { 93 target = new JsonItem() { 94 Name = name, 95 Path = name, 96 Children = new List<JsonItem>() 97 }; 98 col.Add(target); 99 } 100 return target; 101 } 89 102 90 private static void SelectConfigurableItems(InstData instData) { 91 foreach (var item in instData.ParameterizedItems.Values) { 92 if (item.Parameters != null) 93 AddConfigurableItems(item.Parameters, instData); 103 // rebuilds item tree with splitting paths of each jsonitem 104 private static void RebuildTree(InstData instData) { 105 List<JsonItem> values = new List<JsonItem>(); 106 foreach (var x in instData.Objects) { 107 string[] pathParts = x.Key.Split('.'); 108 JsonItem target = RebuildTreeHelper(values, pathParts[0]); 94 109 95 if (item.Operators != null) 96 AddConfigurableItems(item.Operators, instData); 110 for (int i = 1; i < pathParts.Length; ++i) { 111 target = RebuildTreeHelper(target.Children, pathParts[i]); 112 } 113 114 JsonItem.Merge(target, x.Value); 115 } 116 foreach(var val in values) { 117 instData.ResolvedItems.Add(val.Name, val); 97 118 } 98 119 } 99 100 private static void AddConfigurableItems(IEnumerable<JsonItem> items, InstData instData) { 101 foreach (var item in items) 102 if (item.IsConfigurable) 103 instData.ConfigurableItems.Add(item.Path, item); 104 } 105 106 private static void ResolveReferences(InstData instData) { 107 foreach(var x in instData.ParameterizedItems.Values) 108 foreach (var p in x.Parameters) 109 if (p.Value is string) { 110 string key = p.Path; 111 if (p.Range != null) 112 key = $"{p.Path}.{p.Value.Cast<string>()}"; 113 114 if (instData.ParameterizedItems.TryGetValue(key, out JsonItem value)) 115 p.Reference = value; 116 } 117 } 118 120 119 121 private static void MergeTemplateWithConfig(InstData instData) { 120 122 foreach (JObject obj in instData.Config) { 121 123 // build item from config object 122 JsonItem item = JsonItem.BuildJsonItem(obj , instData.TypeList);124 JsonItem item = JsonItem.BuildJsonItem(obj); 123 125 // override default value 124 if (instData. ConfigurableItems.TryGetValue(item.Path, out JsonItem param)) {126 if (instData.Objects.TryGetValue(item.Path, out JsonItem param)) { 125 127 param.Value = item.Value; 126 128 // override ActualName (for LookupParameters) 127 129 if (param.ActualName != null) 128 130 param.ActualName = item.ActualName; 129 } else throw new InvalidDataException($"No {Constants.FreeParameters.Trim('s')}with path='{item.Path}' defined!");131 } else throw new InvalidDataException($"No parameter with path='{item.Path}' defined!"); 130 132 } 131 133 } … … 133 135 private static JsonItem GetData(string key, InstData instData) 134 136 { 135 if (instData. ParameterizedItems.TryGetValue(key, out JsonItem value))137 if (instData.ResolvedItems.TryGetValue(key, out JsonItem value)) 136 138 return value; 137 139 else 138 140 throw new InvalidDataException($"Type of item '{key}' is not defined!"); 139 141 } 140 141 private static T CreateObject<T>(JsonItem data, InstData instData) {142 if (instData.TypeList.TryGetValue(data.Name, out string typeName)) {143 Type type = Type.GetType(typeName);144 return (T)Activator.CreateInstance(type);145 } else throw new TypeLoadException($"Cannot find AssemblyQualifiedName for {data.Name}.");146 }147 142 #endregion 148 143 } -
branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/JsonItem.cs
r17374 r17379 28 28 string oldName = Name; 29 29 name = value; 30 // replace name in path if path != null 30 31 if (Path != null) { 31 32 var parts = Path.Split('.'); 32 for (int i = 0; i < parts.Length; ++i) 33 if (parts[i] == oldName) 34 parts[i] = Name; 35 33 parts[Array.IndexOf(parts, oldName)] = name; 36 34 Path = string.Join(".", parts); 37 35 } else … … 42 40 } 43 41 } 44 public string Type { get; set; }45 42 public string Path { get; set; } 46 public IList<JsonItem> Parameters { get; set; } // -> für flachen aufbau -> childs? 47 public IList<JsonItem> Operators { get; set; } 43 public IList<JsonItem> Children { get; set; } 48 44 public object Value { 49 45 get => value; … … 62 58 public string ActualName { get; set; } 63 59 64 #region JsonIgnore Properties65 [JsonIgnore]66 public JsonItem Reference { get; set; }67 68 [JsonIgnore]69 public bool IsConfigurable => (Value != null && Range != null);70 71 [JsonIgnore]72 public bool IsParameterizedItem => Parameters != null;73 #endregion74 75 60 #region Public Static Methods 76 61 public static void Merge(JsonItem target, JsonItem from) { 77 62 target.Name = from.Name ?? target.Name; 78 target.Type = from.Type ?? target.Type;79 63 target.Range = from.Range ?? target.Range; 80 64 target.Path = from.Path ?? target.Path; 81 65 target.Value = from.Value ?? target.Value; 82 target.Reference = from.Reference ?? target.Reference;83 66 target.ActualName = from.ActualName ?? target.ActualName; 84 target.Parameters = from.Parameters ?? target.Parameters; 85 target.Operators = from.Operators ?? target.Operators; 67 if(target.Children != null) { 68 if (from.Children != null) 69 ((List<JsonItem>)from.Children).AddRange(target.Children); 70 } else { 71 target.Children = from.Children; 72 } 86 73 } 87 74 #endregion … … 89 76 #region Public Methods 90 77 public void AddParameter(JsonItem item) { 91 if ( Parameters== null)92 Parameters= new List<JsonItem>();93 Parameters.Add(item);78 if (Children == null) 79 Children = new List<JsonItem>(); 80 Children.Add(item); 94 81 item.Path = $"{Path}.{item.Name}"; 95 82 item.UpdatePath(); … … 97 84 98 85 public void UpdatePath() { 99 if (Parameters != null) 100 UpdatePathHelper(Parameters); 101 102 if (Operators != null) 103 UpdatePathHelper(Operators); 104 105 if (Reference != null) 106 UpdatePathHelper(Reference); 86 if (Children != null) 87 UpdatePathHelper(Children); 107 88 } 108 89 #endregion 109 90 110 91 #region Helper 111 private void UpdatePathHelper(params JsonItem[] items) =>112 UpdatePathHelper((IEnumerable<JsonItem>)items);113 114 92 private void UpdatePathHelper(IEnumerable<JsonItem> items) { 115 93 foreach (var item in items) { … … 136 114 b2 = IsInNumericRange(Value); 137 115 } 138 139 116 return b1 || b2; 140 117 } … … 166 143 (((T)max).CompareTo(value) == 1 || ((T)max).CompareTo(value) == 0); 167 144 } 168 169 145 #endregion 170 146 171 147 #region BuildJsonItemMethods 172 public static JsonItem BuildJsonItem(JObject obj , IDictionary<string, string> typeList) {148 public static JsonItem BuildJsonItem(JObject obj) { 173 149 object val = obj[nameof(Value)]?.ToObject<object>(); 174 if (val is JContainer) { 175 //try { 176 val = ((JContainer)val).ToObject<object[]>(); 177 /*} catch (Exception) { } 178 try { 179 val = ((JContainer)val).ToObject<object[,]>(); 180 } catch (Exception) { }*/ 181 } 150 if (val is JContainer jContainer) // for resolving array values 151 val = jContainer.ToObject<object[]>(); 182 152 183 184 153 return new JsonItem() { 185 154 Name = obj[nameof(Name)]?.ToString(), … … 187 156 Value = val, 188 157 Range = obj[nameof(Range)]?.ToObject<object[]>(), 189 Type = GetType(obj[nameof(Path)]?.ToObject<string>(), typeList), 190 ActualName = obj[nameof(ActualName)]?.ToString(), 191 Parameters = PopulateParameters(obj, typeList), 192 Operators = PopulateOperators(obj, typeList) 158 ActualName = obj[nameof(ActualName)]?.ToString() 193 159 }; 194 }195 196 private static string GetType(string path, IDictionary<string, string> typeList) {197 if (!string.IsNullOrEmpty(path))198 if (typeList.TryGetValue(path, out string value))199 return value;200 return null;201 }202 203 private static IList<JsonItem> PopulateParameters(JObject obj, IDictionary<string, string> typeList) {204 IList<JsonItem> list = new List<JsonItem>();205 206 // add staticParameters207 if (obj[Constants.StaticParameters] != null)208 foreach (JObject param in obj[Constants.StaticParameters])209 list.Add(BuildJsonItem(param, typeList));210 211 // merge staticParameter with freeParameter212 if (obj[Constants.FreeParameters] != null) {213 foreach (JObject param in obj[Constants.FreeParameters]) {214 JsonItem tmp = BuildJsonItem(param, typeList);215 216 // search staticParameter from list217 JsonItem comp = null;218 foreach (var p in list)219 if (p.Name == tmp.Name) comp = p;220 if (comp == null)221 throw new InvalidDataException($"Invalid {Constants.FreeParameters.Trim('s')}: '{tmp.Name}'!");222 223 JsonItem.Merge(comp, tmp);224 }225 }226 return list;227 }228 229 private static IList<JsonItem> PopulateOperators(JObject obj, IDictionary<string, string> typeList) {230 IList<JsonItem> list = new List<JsonItem>();231 JToken operators = obj[nameof(JsonItem.Operators)];232 if (operators != null)233 foreach (JObject sp in operators)234 list.Add(BuildJsonItem(sp, typeList));235 return list;236 160 } 237 161 #endregion -
branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/JsonItemConverter.cs
r17374 r17379 34 34 Converters.Add(type, new ConverterPriorityContainer() { Converter = converter, Priority = priority }); 35 35 } 36 37 36 38 37 public static void Register(string atticGuid, IJsonItemConverter converter, int priority) => … … 126 125 127 126 Register("EE612297-B1AF-42D2-BF21-AF9A2D42791C", new RegressionProblemDataConverter(), 20); 128 129 // ISymbol130 /*131 Register("25137f88-66b9-48d7-a2bd-60190082e044",132 new ConfigurableConverter()133 .Primitive("InitialFrequency", ElementType.Property, new object[] { 0.0, 1.0 })134 .Primitive("Enabled", ElementType.Property, true)135 .Primitive("MinimumArity", ElementType.Property, 0)136 .Primitive("MaximumArity", ElementType.Property, 10),137 5);138 */139 // SymbolicRegressionProblem140 /*141 Register("7DDCF683-96FC-4F70-BF4F-FE3A0B0DE6E0",142 new ConfigurableConverter()143 .144 10);145 */146 147 // Dataset148 /*149 Register("49F4D145-50D7-4497-8D8A-D190CD556CC8",150 new ConfigurableConverter() //TODO: set guid to enable "inheritance"?151 .PrimitiveEnumerable("storableData", ElementType.Field, new double[,] { }),152 5);153 */154 // ItemCollection<>155 /*156 Register("0BD4F01E-2D52-4E41-AEF8-611F10856D90",157 new ConfigurableConverter()158 .This((o, t) => {159 dynamic itemList = o as dynamic;160 IList<JsonItem> jsonItems = new List<JsonItem>();161 foreach (var obj in itemList) {162 IItem item = obj as IItem;163 jsonItems.Add(Extract(item));164 }165 return jsonItems;166 }),167 5);168 */169 // IItemList<>170 /*171 Register("466747d2-6a73-495b-ac68-7b0199d0f830",172 new ConfigurableConverter()173 .This((o, t) => {174 dynamic itemList = o as dynamic;175 IList<JsonItem> jsonItems = new List<JsonItem>();176 foreach (var obj in itemList) {177 IItem item = obj as IItem;178 jsonItems.Add(Extract(item));179 }180 return jsonItems;181 }),182 6);183 */184 // ICheckedItemList<>185 /*186 Register("ba4a82ca-92eb-47a1-95a7-f41f6ef470f4",187 new ConfigurableConverter()188 .This((o,t) => {189 dynamic itemList = o as dynamic;190 IList<JsonItem> jsonItems = new List<JsonItem>();191 int count = 0;192 foreach(var obj in itemList) {193 IItem item = obj as IItem;194 JsonItem checkedStatus = new JsonItem() {195 Name = "Checked",196 Value = itemList.ItemChecked(obj),197 Range = new object[] { false, true }198 };199 JsonItem value = Extract(item);200 201 jsonItems.Add(new JsonItem() {202 Name = item.ItemName + count++,203 Parameters = new JsonItem[] {204 checkedStatus, value205 },206 Type = item.GetType().AssemblyQualifiedName207 });208 }209 return jsonItems;210 }),211 6);212 */213 //ISymbolicExpressionGrammar - "1f6afcbe-b309-44e2-8d35-2d33eaeb9649"214 //ISymbolicExpressionGrammarBase - "119f5e94-bc7d-42fc-a48b-ac0230115ef2"215 /*216 Register("119f5e94-bc7d-42fc-a48b-ac0230115ef2",217 new ConfigurableConverter()218 .Enumerable("Symbols", ElementType.Property, (o,t) => new JsonItem[] { Extract(o as IItem) }),219 10);220 */221 127 } 222 128 } -
branches/3026_IntegrationIntoSymSpace/Heuristiclab.ConfigStarter/Program.cs
r17374 r17379 17 17 namespace Heuristiclab.ConfigStarter { 18 18 public class Program { 19 20 private static string Reduce(string str) =>21 str22 .Replace(" ", "")23 .Replace("-", "")24 .Replace("`", "")25 .Replace(".", "")26 .Replace("<", "")27 .Replace(">", "")28 .Replace("(", "_")29 .Replace(")", "_");30 31 private static void Visualize(JsonItem item, StringBuilder sb) {32 sb.Append($" {item.GetHashCode()} [label=\"{item.Name}\"];\n");33 foreach (var i in item.Parameters) {34 sb.Append($" {item.GetHashCode()} -> {i.GetHashCode()};\n");35 }36 foreach(var i in item.Parameters) {37 Visualize(i, sb);38 }39 }40 19 41 20 public static void Main(string[] args) { … … 64 43 SymbolicRegressionSingleObjectiveProblem prop = new SymbolicRegressionSingleObjectiveProblem(); 65 44 66 alg.Problem = prop;45 alg.Problem = tsp; 67 46 68 alg.Engine = new SequentialEngine();69 Task t = alg.StartAsync();70 Thread.Sleep(1000);71 alg.Stop();72 73 StorableConverter storableConverter = new StorableConverter();74 JsonItem item = storableConverter.Extract(alg);75 76 StringBuilder sb = new StringBuilder();77 78 //Visualize(item, sb);79 80 //File.WriteAllText(@"C:\Workspace\item.gv", $"digraph G {{\n{sb.ToString()}}}");81 82 83 //Console.WriteLine(alg);84 47 File.WriteAllText(@"C:\Workspace\Template.json", JCGenerator.GenerateTemplate(alg)); 85 48 JCInstantiator.Instantiate(@"C:\Workspace\Template.json"); 86 49 /* 87 50 List<ICommandLineArgument> arguments = new List<ICommandLineArgument>();
Note: See TracChangeset
for help on using the changeset viewer.