Free cookie consent management tool by TermsFeed Policy Generator

Changeset 17409


Ignore:
Timestamp:
01/28/20 12:14:21 (4 years ago)
Author:
gkronber
Message:

#2925: merged r17255:17402 from trunk to branch

Location:
branches/2925_AutoDiffForDynamicalModels
Files:
48 edited
4 copied

Legend:

Unmodified
Added
Removed
  • branches/2925_AutoDiffForDynamicalModels

  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Algorithms.DataAnalysis

  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Algorithms.DataAnalysis/3.4

  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Algorithms.DataAnalysis/3.4/GradientBoostedTrees/GradientBoostedTreesModelSurrogate.cs

    r17246 r17409  
    2424using System.Collections.Generic;
    2525using System.Linq;
     26using HEAL.Attic;
    2627using HeuristicLab.Common;
    2728using HeuristicLab.Core;
    28 using HEAL.Attic;
    2929using HeuristicLab.Problems.DataAnalysis;
    3030
     
    3838    // don't store the actual model!
    3939    // the actual model is only recalculated when necessary
     40    private IGradientBoostedTreesModel fullModel;
    4041    private readonly Lazy<IGradientBoostedTreesModel> actualModel;
    4142    private IGradientBoostedTreesModel ActualModel {
     
    4849    private readonly uint seed;
    4950    [Storable]
    50     private ILossFunction lossFunction;
     51    private readonly ILossFunction lossFunction;
    5152    [Storable]
    52     private double r;
     53    private readonly double r;
    5354    [Storable]
    54     private double m;
     55    private readonly double m;
    5556    [Storable]
    56     private double nu;
     57    private readonly double nu;
    5758    [Storable]
    58     private int iterations;
     59    private readonly int iterations;
    5960    [Storable]
    60     private int maxSize;
     61    private readonly int maxSize;
    6162
    6263
     
    6970    [StorableConstructor]
    7071    private GradientBoostedTreesModelSurrogate(StorableConstructorFlag _) : base(_) {
    71       actualModel = new Lazy<IGradientBoostedTreesModel>(() => RecalculateModel());
     72      actualModel = CreateLazyInitFunc();
    7273    }
    7374
    7475    private GradientBoostedTreesModelSurrogate(GradientBoostedTreesModelSurrogate original, Cloner cloner)
    7576      : base(original, cloner) {
    76       IGradientBoostedTreesModel clonedModel = null;
    77       if (original.actualModel.IsValueCreated) clonedModel = cloner.Clone(original.ActualModel);
    78       actualModel = new Lazy<IGradientBoostedTreesModel>(CreateLazyInitFunc(clonedModel)); // only capture clonedModel in the closure
    79 
     77      // clone data which is necessary to rebuild the model
    8078      this.trainingProblemData = cloner.Clone(original.trainingProblemData);
    8179      this.lossFunction = cloner.Clone(original.lossFunction);
     
    8684      this.m = original.m;
    8785      this.nu = original.nu;
     86
     87      // clone full model if it has already been created
     88      if (original.fullModel != null) this.fullModel = cloner.Clone(original.fullModel);
     89      actualModel = CreateLazyInitFunc();
    8890    }
    8991
    90     private Func<IGradientBoostedTreesModel> CreateLazyInitFunc(IGradientBoostedTreesModel clonedModel) {
    91       return () => {
    92         return clonedModel ?? RecalculateModel();
    93       };
     92    private Lazy<IGradientBoostedTreesModel> CreateLazyInitFunc() {
     93      return new Lazy<IGradientBoostedTreesModel>(() => {
     94        if (fullModel == null) fullModel = RecalculateModel();
     95        return fullModel;
     96      });
    9497    }
    9598
     
    107110      this.nu = nu;
    108111
    109       actualModel = new Lazy<IGradientBoostedTreesModel>(() => RecalculateModel());
     112      actualModel = CreateLazyInitFunc();
    110113    }
    111114
    112     // wrap an actual model in a surrograte
     115    // wrap an actual model in a surrogate
    113116    public GradientBoostedTreesModelSurrogate(IGradientBoostedTreesModel model, IRegressionProblemData trainingProblemData, uint seed,
    114117      ILossFunction lossFunction, int iterations, int maxSize, double r, double m, double nu)
    115118      : this(trainingProblemData, seed, lossFunction, iterations, maxSize, r, m, nu) {
    116       actualModel = new Lazy<IGradientBoostedTreesModel>(() => model);
     119      fullModel = model;
    117120    }
    118121
     
    135138
    136139    public IEnumerable<IRegressionModel> Models {
    137       get {
    138         return ActualModel.Models;
    139       }
     140      get { return ActualModel.Models; }
    140141    }
    141142
    142143    public IEnumerable<double> Weights {
    143       get {
    144         return ActualModel.Weights;
    145       }
     144      get { return ActualModel.Weights; }
    146145    }
    147146  }
  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Algorithms.DataAnalysis/3.4/RandomForest/RandomForestModelSurrogate.cs

    r17246 r17409  
    3535    #region parameters for recalculation of the model
    3636    [Storable]
    37     private int seed;
     37    private readonly int seed;
    3838    [Storable]
    39     private IDataAnalysisProblemData originalTrainingData;
     39    private readonly IDataAnalysisProblemData originalTrainingData;
    4040    [Storable]
    41     private double[] classValues;
     41    private readonly double[] classValues;
    4242    [Storable]
    43     private int nTrees;
     43    private readonly int nTrees;
    4444    [Storable]
    45     private double r;
     45    private readonly double r;
    4646    [Storable]
    47     private double m;
     47    private readonly double m;
    4848    #endregion
     49
    4950
    5051    // don't store the actual model!
    5152    // the actual model is only recalculated when necessary
     53    private IRandomForestModel fullModel = null;
    5254    private readonly Lazy<IRandomForestModel> actualModel;
     55
    5356    private IRandomForestModel ActualModel {
    5457      get { return actualModel.Value; }
     
    7477      this.m = m;
    7578
    76       actualModel = new Lazy<IRandomForestModel>(() => RecalculateModel());
     79      actualModel = CreateLazyInitFunc();
    7780    }
    7881
    79     // wrap an actual model in a surrograte
     82    // wrap an actual model in a surrogate
    8083    public RandomForestModelSurrogate(IRandomForestModel model, string targetVariable, IDataAnalysisProblemData originalTrainingData,
    81       int seed, int nTrees, double r, double m, double[] classValues = null) : this(targetVariable, originalTrainingData, seed, nTrees, r, m, classValues) {
    82       actualModel = new Lazy<IRandomForestModel>(() => model);
     84      int seed, int nTrees, double r, double m, double[] classValues = null)
     85      : this(targetVariable, originalTrainingData, seed, nTrees, r, m, classValues) {
     86      fullModel = model;
    8387    }
    8488
    8589    [StorableConstructor]
    8690    private RandomForestModelSurrogate(StorableConstructorFlag _) : base(_) {
    87       actualModel = new Lazy<IRandomForestModel>(() => RecalculateModel());
     91      actualModel = CreateLazyInitFunc();
    8892    }
    8993
    9094    private RandomForestModelSurrogate(RandomForestModelSurrogate original, Cloner cloner) : base(original, cloner) {
    91       IRandomForestModel clonedModel = null;
    92       if (original.actualModel.IsValueCreated) clonedModel = cloner.Clone(original.ActualModel);
    93       actualModel = new Lazy<IRandomForestModel>(CreateLazyInitFunc(clonedModel)); // only capture clonedModel in the closure
    94 
    9595      // clone data which is necessary to rebuild the model
    9696      this.originalTrainingData = cloner.Clone(original.originalTrainingData);
     
    100100      this.r = original.r;
    101101      this.m = original.m;
    102     }
    103102
    104     private Func<IRandomForestModel> CreateLazyInitFunc(IRandomForestModel clonedModel) {
    105       return () => {
    106         return clonedModel ?? RecalculateModel();
    107       };
     103      // clone full model if it has already been created
     104      if (original.fullModel != null) this.fullModel = cloner.Clone(original.fullModel);
     105      actualModel = CreateLazyInitFunc();
    108106    }
    109107
    110108    public override IDeepCloneable Clone(Cloner cloner) {
    111109      return new RandomForestModelSurrogate(this, cloner);
     110    }
     111
     112    private Lazy<IRandomForestModel> CreateLazyInitFunc() {
     113      return new Lazy<IRandomForestModel>(() => {
     114        if (fullModel == null) fullModel = RecalculateModel();
     115        return fullModel;
     116      });
    112117    }
    113118
  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Clients.Hive.Administrator

  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Clients.Hive.Administrator/3.3/Views/ProjectView.Designer.cs

    r16662 r17409  
    3939      this.endLabel = new System.Windows.Forms.Label();
    4040      this.indefiniteCheckBox = new System.Windows.Forms.CheckBox();
    41       this.createdTextBox = new System.Windows.Forms.TextBox();     
     41      this.createdTextBox = new System.Windows.Forms.TextBox();
    4242      this.toolTip = new System.Windows.Forms.ToolTip(this.components);
     43      this.refreshButton = new System.Windows.Forms.Button();
    4344      this.SuspendLayout();
    4445      //
     
    6869      this.nameLabel.Name = "nameLabel";
    6970      this.nameLabel.Size = new System.Drawing.Size(38, 13);
    70       this.nameLabel.TabIndex = 0;
     71      this.nameLabel.TabIndex = 2;
    7172      this.nameLabel.Text = "Name:";
    7273      //
     
    7879      this.nameTextBox.Name = "nameTextBox";
    7980      this.nameTextBox.Size = new System.Drawing.Size(464, 20);
    80       this.nameTextBox.TabIndex = 2;
     81      this.nameTextBox.TabIndex = 3;
    8182      this.nameTextBox.TextChanged += new System.EventHandler(this.nameTextBox_TextChanged);
    8283      this.nameTextBox.Validating += new System.ComponentModel.CancelEventHandler(this.nameTextBox_Validating);
     
    8889      this.descriptionLabel.Name = "descriptionLabel";
    8990      this.descriptionLabel.Size = new System.Drawing.Size(63, 13);
    90       this.descriptionLabel.TabIndex = 0;
     91      this.descriptionLabel.TabIndex = 4;
    9192      this.descriptionLabel.Text = "Description:";
    9293      //
     
    99100      this.descriptionTextBox.Name = "descriptionTextBox";
    100101      this.descriptionTextBox.Size = new System.Drawing.Size(464, 98);
    101       this.descriptionTextBox.TabIndex = 3;
     102      this.descriptionTextBox.TabIndex = 5;
    102103      this.descriptionTextBox.TextChanged += new System.EventHandler(this.descriptionTextBox_TextChanged);
    103104      //
    104       // ownerLabel
    105       //
    106       this.ownerLabel.AutoSize = true;
    107       this.ownerLabel.Location = new System.Drawing.Point(3, 167);
    108       this.ownerLabel.Name = "ownerLabel";
    109       this.ownerLabel.Size = new System.Drawing.Size(41, 13);
    110       this.ownerLabel.TabIndex = 0;
    111       this.ownerLabel.Text = "Owner:";
    112       //
    113105      // ownerComboBox
    114106      //
    115       //this.ownerComboBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
    116       //      | System.Windows.Forms.AnchorStyles.Right)));
    117107      this.ownerComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
    118108      this.ownerComboBox.FormattingEnabled = true;
     
    120110      this.ownerComboBox.Name = "ownerComboBox";
    121111      this.ownerComboBox.Size = new System.Drawing.Size(200, 21);
    122       this.ownerComboBox.TabIndex = 4;
     112      this.ownerComboBox.TabIndex = 7;
    123113      this.ownerComboBox.SelectedIndexChanged += new System.EventHandler(this.ownerComboBox_SelectedIndexChanged);
     114      //
     115      // ownerLabel
     116      //
     117      this.ownerLabel.AutoSize = true;
     118      this.ownerLabel.Location = new System.Drawing.Point(3, 167);
     119      this.ownerLabel.Name = "ownerLabel";
     120      this.ownerLabel.Size = new System.Drawing.Size(41, 13);
     121      this.ownerLabel.TabIndex = 6;
     122      this.ownerLabel.Text = "Owner:";
    124123      //
    125124      // createdLabel
     
    129128      this.createdLabel.Name = "createdLabel";
    130129      this.createdLabel.Size = new System.Drawing.Size(47, 13);
    131       this.createdLabel.TabIndex = 8;
     130      this.createdLabel.TabIndex = 9;
    132131      this.createdLabel.Text = "Created:";
    133132      //
     
    135134      //
    136135      this.startDateTimePicker.CustomFormat = "ddd, dd.MM.yyyy, HH:mm:ss";
    137       this.startDateTimePicker.Enabled = false;
    138136      this.startDateTimePicker.Format = System.Windows.Forms.DateTimePickerFormat.Custom;
    139137      this.startDateTimePicker.Location = new System.Drawing.Point(72, 216);
    140138      this.startDateTimePicker.Name = "startDateTimePicker";
    141139      this.startDateTimePicker.Size = new System.Drawing.Size(200, 20);
    142       this.startDateTimePicker.TabIndex = 9;
    143       this.startDateTimePicker.ValueChanged += new System.EventHandler(this.startDateTimePicker_ValueChanged);     
     140      this.startDateTimePicker.TabIndex = 12;
     141      this.startDateTimePicker.ValueChanged += new System.EventHandler(this.startDateTimePicker_ValueChanged);
    144142      //
    145143      // startLabel
     
    149147      this.startLabel.Name = "startLabel";
    150148      this.startLabel.Size = new System.Drawing.Size(32, 13);
    151       this.startLabel.TabIndex = 10;
     149      this.startLabel.TabIndex = 11;
    152150      this.startLabel.Text = "Start:";
    153151      //
     
    155153      //
    156154      this.endDateTimePicker.CustomFormat = "ddd, dd.MM.yyyy, HH:mm:ss";
    157       this.endDateTimePicker.Enabled = false;
    158155      this.endDateTimePicker.Format = System.Windows.Forms.DateTimePickerFormat.Custom;
    159156      this.endDateTimePicker.Location = new System.Drawing.Point(72, 243);
    160157      this.endDateTimePicker.Name = "endDateTimePicker";
    161158      this.endDateTimePicker.Size = new System.Drawing.Size(200, 20);
    162       this.endDateTimePicker.TabIndex = 11;
     159      this.endDateTimePicker.TabIndex = 14;
    163160      this.endDateTimePicker.ValueChanged += new System.EventHandler(this.endDateTimePicker_ValueChanged);
    164161      //
     
    169166      this.endLabel.Name = "endLabel";
    170167      this.endLabel.Size = new System.Drawing.Size(29, 13);
    171       this.endLabel.TabIndex = 10;
     168      this.endLabel.TabIndex = 13;
    172169      this.endLabel.Text = "End:";
    173170      //
     
    178175      this.indefiniteCheckBox.Name = "indefiniteCheckBox";
    179176      this.indefiniteCheckBox.Size = new System.Drawing.Size(69, 17);
    180       this.indefiniteCheckBox.TabIndex = 13;
     177      this.indefiniteCheckBox.TabIndex = 15;
    181178      this.indefiniteCheckBox.Text = "Indefinite";
    182179      this.indefiniteCheckBox.UseVisualStyleBackColor = true;
     
    189186      this.createdTextBox.ReadOnly = true;
    190187      this.createdTextBox.Size = new System.Drawing.Size(200, 20);
    191       this.createdTextBox.TabIndex = 14;
     188      this.createdTextBox.TabIndex = 10;
     189      //
     190      // refreshButton
     191      //
     192      this.refreshButton.Image = HeuristicLab.Common.Resources.VSImageLibrary.Refresh;
     193      this.refreshButton.Location = new System.Drawing.Point(278, 162);
     194      this.refreshButton.Name = "refreshButton";
     195      this.refreshButton.Size = new System.Drawing.Size(24, 24);
     196      this.refreshButton.TabIndex = 8;
     197      this.refreshButton.UseVisualStyleBackColor = true;
     198      this.refreshButton.Click += new System.EventHandler(this.refreshButton_Click);
    192199      //
    193200      // ProjectView
     
    195202      this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
    196203      this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
     204      this.Controls.Add(this.refreshButton);
    197205      this.Controls.Add(this.createdTextBox);
    198206      this.Controls.Add(this.indefiniteCheckBox);
     
    213221      this.Size = new System.Drawing.Size(539, 271);
    214222      this.Load += new System.EventHandler(this.ProjectView_Load);
    215       this.Disposed += new System.EventHandler(this.ProjectView_Disposed);
    216223      this.ResumeLayout(false);
    217224      this.PerformLayout();
     
    235242    private System.Windows.Forms.Label endLabel;
    236243    private System.Windows.Forms.CheckBox indefiniteCheckBox;
    237     private System.Windows.Forms.TextBox createdTextBox;   
     244    private System.Windows.Forms.TextBox createdTextBox;
    238245    private System.Windows.Forms.ToolTip toolTip;
     246    private System.Windows.Forms.Button refreshButton;
    239247  }
    240248}
  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Clients.Hive.Administrator/3.3/Views/ProjectView.cs

    r17246 r17409  
    2828using HeuristicLab.Core.Views;
    2929using HeuristicLab.MainForm;
     30using Tpl = System.Threading.Tasks;
    3031
    3132namespace HeuristicLab.Clients.Hive.Administrator.Views {
     
    3334  [Content(typeof(Project), IsDefaultView = true)]
    3435  public partial class ProjectView : ItemView {
    35     private readonly object locker = new object();
    36 
    3736    public new Project Content {
    3837      get { return (Project)base.Content; }
     
    5857    }
    5958
    60     protected void RegisterControlEvents() {
    61       nameTextBox.TextChanged += nameTextBox_TextChanged;
    62       nameTextBox.Validating += nameTextBox_Validating;
    63       descriptionTextBox.TextChanged += descriptionTextBox_TextChanged;
    64       ownerComboBox.SelectedIndexChanged += ownerComboBox_SelectedIndexChanged;
    65       startDateTimePicker.ValueChanged += startDateTimePicker_ValueChanged;
    66       endDateTimePicker.ValueChanged += endDateTimePicker_ValueChanged;
    67       indefiniteCheckBox.CheckedChanged += indefiniteCheckBox_CheckedChanged;
    68     }
    69 
    70     protected void DeregisterControlEvents() {
    71       nameTextBox.TextChanged -= nameTextBox_TextChanged;
    72       nameTextBox.Validating -= nameTextBox_Validating;
    73       descriptionTextBox.TextChanged -= descriptionTextBox_TextChanged;
    74       ownerComboBox.SelectedIndexChanged -= ownerComboBox_SelectedIndexChanged;
    75       startDateTimePicker.ValueChanged -= startDateTimePicker_ValueChanged;
    76       endDateTimePicker.ValueChanged -= endDateTimePicker_ValueChanged;
    77       indefiniteCheckBox.CheckedChanged -= indefiniteCheckBox_CheckedChanged;
    78     }
    79 
    8059    protected override void OnContentChanged() {
    8160      base.OnContentChanged();
    82       DeregisterControlEvents();
     61      UpdateView();
     62    }
     63
     64    private void UpdateView() {
    8365      if (Content == null) {
    8466        idTextBox.Clear();
     
    9476        nameTextBox.Text = Content.Name;
    9577        descriptionTextBox.Text = Content.Description;
    96 
    97         if (AccessClient.Instance.UsersAndGroups != null) {
    98           var users = AccessClient.Instance.UsersAndGroups.OfType<LightweightUser>();
    99           if (!Content.ParentProjectId.HasValue) users = users.Where(x => x.Roles.Select(y => y.Name).Contains(HiveRoles.Administrator));
    100           var projectOwnerId = Content.OwnerUserId;
    101           ownerComboBox.DataSource = users.OrderBy(x => x.UserName).ToList();
    102           ownerComboBox.SelectedItem = users.FirstOrDefault(x => x.Id == projectOwnerId);
    103         }
    104 
     78        ownerComboBox.SelectedItem = AccessClient.Instance.UsersAndGroups?.OfType<LightweightUser>().SingleOrDefault(x => x.Id == Content.OwnerUserId);
    10579        createdTextBox.Text = Content.DateCreated.ToString("ddd, dd.MM.yyyy, HH:mm:ss");
    10680        startDateTimePicker.Value = Content.StartDate;
    107 
     81        endDateTimePicker.Value = Content.EndDate.GetValueOrDefault(Content.StartDate);
    10882        indefiniteCheckBox.Checked = !Content.EndDate.HasValue;
    109         if (!indefiniteCheckBox.Checked) endDateTimePicker.Value = Content.EndDate.Value;
    110         else endDateTimePicker.Value = Content.StartDate;
    111         endDateTimePicker.Enabled = !indefiniteCheckBox.Checked;
    112       }
    113       SetEnabledStateOfControls();
    114       RegisterControlEvents();
    115     }
    116 
    117     protected override void SetEnabledStateOfControls() {
    118       base.SetEnabledStateOfControls();
    119       bool enabled = Content != null && !Locked && !ReadOnly;
    120       nameTextBox.Enabled = enabled;
    121       descriptionTextBox.Enabled = enabled;
    122       ownerComboBox.Enabled = enabled;
    123       createdTextBox.Enabled = enabled;
    124       startDateTimePicker.Enabled = enabled;
    125       endDateTimePicker.Enabled = enabled && Content.EndDate.HasValue;
    126       indefiniteCheckBox.Enabled = enabled;
    127 
    128       if (Content != null) {
    129         //var parentProject = HiveAdminClient.Instance.GetAvailableProjectAncestors(Content.Id).LastOrDefault();
    130         var parentProject = HiveAdminClient.Instance.Projects.FirstOrDefault(x => x.Id == Content.ParentProjectId);
    131         if ((!IsAdmin() && (parentProject == null || parentProject.EndDate.HasValue))
    132            || (IsAdmin() && parentProject != null && parentProject.EndDate.HasValue)) {
    133           indefiniteCheckBox.Enabled = false;
    134         }
    135 
    136         if (Content.Id != Guid.Empty && !IsAdmin() && !HiveAdminClient.Instance.CheckOwnershipOfParentProject(Content, UserInformation.Instance.User.Id)) {
    137           ownerComboBox.Enabled = false;
    138           startDateTimePicker.Enabled = false;
    139           endDateTimePicker.Enabled = false;
    140           indefiniteCheckBox.Enabled = false;
    141         }
    142       }
    143     }
    144     #endregion
    145 
    146     #region Event Handlers
    147     private void Content_PropertyChanged(object sender, PropertyChangedEventArgs e) {
    148       if (InvokeRequired) Invoke((Action<object, PropertyChangedEventArgs>)Content_PropertyChanged, sender, e);
    149       else OnContentChanged();
    150     }
    151 
    152     private void AccessClient_Instance_Refreshing(object sender, EventArgs e) {
    153       if (InvokeRequired) Invoke((Action<object, EventArgs>)AccessClient_Instance_Refreshing, sender, e);
    154       else {
    155         Progress.Show(this, "Refreshing ...", ProgressMode.Indeterminate);
    156         SetEnabledStateOfControls();
    157       }
    158     }
    159 
    160     private void AccessClient_Instance_Refreshed(object sender, EventArgs e) {
    161       if (InvokeRequired) Invoke((Action<object, EventArgs>)AccessClient_Instance_Refreshed, sender, e);
    162       else {
    163         Progress.Hide(this);
    164         SetEnabledStateOfControls();
    165       }
    166     }
    167 
    168     private async void ProjectView_Load(object sender, EventArgs e) {
    169       await SecurityExceptionUtil.TryAsyncAndReportSecurityExceptions(
    170         action: () => UpdateUsers(),
    171         finallyCallback: () => {
    172           ownerComboBox.SelectedIndexChanged -= ownerComboBox_SelectedIndexChanged;
    173           var users = AccessClient.Instance.UsersAndGroups.OfType<LightweightUser>();
    174           if (Content != null && !Content.ParentProjectId.HasValue) users = users.Where(x => x.Roles.Select(y => y.Name).Contains(HiveRoles.Administrator));
    175           var projectOwnerId = Content != null ? Content.OwnerUserId : (Guid?)null;
    176           ownerComboBox.DataSource = users.OrderBy(x => x.UserName).ToList();
    177           ownerComboBox.SelectedItem = projectOwnerId.HasValue ? users.FirstOrDefault(x => x.Id == projectOwnerId) : null;
    178           ownerComboBox.SelectedIndexChanged += ownerComboBox_SelectedIndexChanged;
    179         });
    180     }
    181 
    182     private void ProjectView_Disposed(object sender, EventArgs e) {
    183       AccessClient.Instance.Refreshed -= AccessClient_Instance_Refreshed;
    184       AccessClient.Instance.Refreshing -= AccessClient_Instance_Refreshing;
    185     }
    186 
    187     private void nameTextBox_Validating(object sender, CancelEventArgs e) {
    188       if (string.IsNullOrEmpty(nameTextBox.Text)) {
    189         MessageBox.Show(
    190           "Project must have a name.",
    191           "HeuristicLab Hive Administrator",
    192           MessageBoxButtons.OK,
    193           MessageBoxIcon.Error);
    194         e.Cancel = true;
    195       }
    196     }
    197 
    198     private void nameTextBox_TextChanged(object sender, EventArgs e) {
    199       if (Content != null && Content.Name != nameTextBox.Text) {
    200         DeregisterContentEvents();
    201         Content.Name = nameTextBox.Text;
    202         RegisterContentEvents();
    203       }
    204     }
    205 
    206     private void descriptionTextBox_TextChanged(object sender, EventArgs e) {
    207       if (Content != null && Content.Description != descriptionTextBox.Text) {
    208         DeregisterContentEvents();
    209         Content.Description = descriptionTextBox.Text;
    210         RegisterContentEvents();
    211       }
    212     }
    213 
    214     private void ownerComboBox_SelectedIndexChanged(object sender, EventArgs e) {
    215       var selectedItem = (LightweightUser)ownerComboBox.SelectedItem;
    216       var selectedOwnerUserId = selectedItem != null ? selectedItem.Id : Guid.Empty;
    217       if (Content != null && Content.OwnerUserId != selectedOwnerUserId) {
    218         DeregisterContentEvents();
    219         Content.OwnerUserId = selectedOwnerUserId;
    220         RegisterContentEvents();
    221       }
    222     }
    223 
    224     private void startDateTimePicker_ValueChanged(object sender, EventArgs e) {
    225       if (Content == null) return;
    226       startDateTimePicker.ValueChanged -= startDateTimePicker_ValueChanged;
    227 
    228       if (!IsAdmin()) {
    229         var parentProject = HiveAdminClient.Instance.GetAvailableProjectAncestors(Content.Id).LastOrDefault();
    230         if (parentProject != null) {
    231           if (startDateTimePicker.Value < parentProject.StartDate)
    232             startDateTimePicker.Value = parentProject.StartDate;
    233         } else {
    234           startDateTimePicker.Value = Content.StartDate;
    235         }
    236       }
    237 
    238       if (!Content.EndDate.HasValue || startDateTimePicker.Value > Content.EndDate)
    239         endDateTimePicker.Value = startDateTimePicker.Value;
    240       if (Content.StartDate != startDateTimePicker.Value) {
    241         DeregisterContentEvents();
    242         Content.StartDate = startDateTimePicker.Value;
    243         RegisterContentEvents();
    244       }
    245 
    246       startDateTimePicker.ValueChanged += startDateTimePicker_ValueChanged;
    247     }
    248 
    249     private void endDateTimePicker_ValueChanged(object sender, EventArgs e) {
    250       if (Content == null) return;
    251       endDateTimePicker.ValueChanged -= endDateTimePicker_ValueChanged;
    252 
    253       if (!IsAdmin()) {
    254         var parentProject = HiveAdminClient.Instance.GetAvailableProjectAncestors(Content.Id).LastOrDefault();
    255         if (parentProject != null) {
    256           if (parentProject.EndDate.HasValue && endDateTimePicker.Value > parentProject.EndDate.Value) {
    257             endDateTimePicker.Value = parentProject.EndDate.Value;
    258           }
    259         } else if (Content.EndDate.HasValue) {
    260           endDateTimePicker.Value = Content.EndDate.Value;
    261         }
    262       }
    263 
    264       if (endDateTimePicker.Value < startDateTimePicker.Value)
    265         endDateTimePicker.Value = startDateTimePicker.Value;
    266       if (Content.EndDate != endDateTimePicker.Value) {
    267         DeregisterContentEvents();
    268         Content.EndDate = endDateTimePicker.Value;
    269         RegisterContentEvents();
    270       }
    271 
    272       endDateTimePicker.ValueChanged += endDateTimePicker_ValueChanged;
    273     }
    274 
    275     private void indefiniteCheckBox_CheckedChanged(object sender, EventArgs e) {
    276       if (Content == null) return;
    277 
    278       var newEndDate = indefiniteCheckBox.Checked ? (DateTime?)null : endDateTimePicker.Value;
    279       endDateTimePicker.Enabled = !indefiniteCheckBox.Checked;
    280       if (Content.EndDate != newEndDate) {
    281         DeregisterContentEvents();
    282         Content.EndDate = newEndDate;
    283         RegisterContentEvents();
    284       }
    285     }
    286     #endregion
    287 
    288     #region Helpers
     83      }
     84    }
     85
     86    private async Tpl.Task UpdateUsersAsync() {
     87      await Tpl.Task.Run(() => UpdateUsers());
     88    }
     89
    28990    private void UpdateUsers() {
     91      // deregister handler to avoid change of content's owner when data source is updated
     92      ownerComboBox.SelectedIndexChanged -= ownerComboBox_SelectedIndexChanged;
    29093      try {
    291         AccessClient.Instance.Refresh();
     94        ownerComboBox.DataSource = null;
     95        SecurityExceptionUtil.TryAndReportSecurityExceptions(AccessClient.Instance.Refresh);
     96        ownerComboBox.DataSource = AccessClient.Instance.UsersAndGroups.OfType<LightweightUser>().OrderBy(x => x.UserName).ToList();
    29297      } catch (AnonymousUserException) {
    29398        ShowHiveInformationDialog();
    294       }
    295     }
    296 
    297     private bool IsAdmin() {
    298       return HiveRoles.CheckAdminUserPermissions();
     99      } finally {
     100        ownerComboBox.SelectedIndexChanged += ownerComboBox_SelectedIndexChanged;
     101      }
    299102    }
    300103
     
    307110      }
    308111    }
     112
     113    protected override void SetEnabledStateOfControls() {
     114      base.SetEnabledStateOfControls();
     115
     116      bool enabled = Content != null && !Locked && !ReadOnly;
     117
     118      nameTextBox.Enabled = enabled;
     119      descriptionTextBox.Enabled = enabled;
     120      ownerComboBox.Enabled = enabled;
     121      refreshButton.Enabled = enabled;
     122      createdTextBox.Enabled = enabled;
     123      startDateTimePicker.Enabled = enabled;
     124      endDateTimePicker.Enabled = enabled && Content.EndDate.HasValue && Content.EndDate > Content.StartDate;
     125      indefiniteCheckBox.Enabled = enabled;
     126
     127      if (Content == null) return;
     128
     129      var parentProject = HiveAdminClient.Instance.Projects.SingleOrDefault(x => x.Id == Content.ParentProjectId);
     130      if (parentProject != null && parentProject.EndDate.HasValue)
     131        indefiniteCheckBox.Enabled = false;
     132
     133      if (Content.Id == Guid.Empty) return; // newly created project
     134      if (HiveRoles.CheckAdminUserPermissions()) return; // admins can edit any project
     135      if (HiveAdminClient.Instance.CheckOwnershipOfParentProject(Content, UserInformation.Instance.User.Id)) return; // owner can edit project
     136
     137      // project was already created and user is neither admin nor owner
     138      ownerComboBox.Enabled = false;
     139      startDateTimePicker.Enabled = false;
     140      endDateTimePicker.Enabled = false;
     141      indefiniteCheckBox.Enabled = false;
     142    }
     143    #endregion
     144
     145    #region Event Handlers
     146    private void ProjectView_Load(object sender, EventArgs e) {
     147      Locked = true;
     148      try {
     149        UpdateUsers();
     150        UpdateView();
     151      } finally {
     152        Locked = false;
     153      }
     154    }
     155
     156    private void Content_PropertyChanged(object sender, PropertyChangedEventArgs e) {
     157      UpdateView();
     158    }
     159
     160    private void nameTextBox_TextChanged(object sender, EventArgs e) {
     161      if (Content == null || Content.Name == nameTextBox.Text) return;
     162      Content.Name = nameTextBox.Text;
     163    }
     164
     165    private void nameTextBox_Validating(object sender, CancelEventArgs e) {
     166      if (!string.IsNullOrEmpty(nameTextBox.Text)) return;
     167
     168      MessageBox.Show("Project must have a name.", "HeuristicLab Hive Administrator", MessageBoxButtons.OK, MessageBoxIcon.Error);
     169      e.Cancel = true;
     170    }
     171
     172    private void descriptionTextBox_TextChanged(object sender, EventArgs e) {
     173      if (Content == null || Content.Description == descriptionTextBox.Text) return;
     174      Content.Description = descriptionTextBox.Text;
     175    }
     176
     177    private void ownerComboBox_SelectedIndexChanged(object sender, EventArgs e) {
     178      if (Content == null) return;
     179
     180      var selectedItem = (LightweightUser)ownerComboBox.SelectedItem;
     181      var selectedOwnerUserId = selectedItem != null ? selectedItem.Id : Guid.Empty;
     182      if (Content.OwnerUserId == selectedOwnerUserId) return;
     183
     184      Content.OwnerUserId = selectedOwnerUserId;
     185    }
     186
     187    private async void refreshButton_Click(object sender, EventArgs e) {
     188      Locked = true;
     189      try {
     190        await UpdateUsersAsync();
     191        UpdateView();
     192      } finally {
     193        Locked = false;
     194      }
     195    }
     196
     197    private void startDateTimePicker_ValueChanged(object sender, EventArgs e) {
     198      if (Content == null || Content.StartDate == startDateTimePicker.Value) return;
     199
     200      string errorMessage = string.Empty;
     201
     202      var parentProject = HiveAdminClient.Instance.Projects.SingleOrDefault(x => x.Id == Content.ParentProjectId);
     203      if (parentProject != null) {
     204        if (startDateTimePicker.Value < parentProject.StartDate) {
     205          errorMessage = "Project cannot start before its parent project has started.";
     206        } else if (startDateTimePicker.Value > parentProject.EndDate) {
     207          errorMessage = "Project cannot start after its parent project has ended.";
     208        }
     209      }
     210
     211      if (startDateTimePicker.Value > endDateTimePicker.Value) {
     212        errorMessage = "Project cannot start after it ends.";
     213      }
     214
     215      if (!string.IsNullOrEmpty(errorMessage)) {
     216        MessageBox.Show(errorMessage, "HeuristicLab Hive Administrator", MessageBoxButtons.OK, MessageBoxIcon.Error);
     217        startDateTimePicker.Value = Content.StartDate;
     218      }
     219
     220      Content.StartDate = startDateTimePicker.Value;
     221    }
     222
     223    private void endDateTimePicker_ValueChanged(object sender, EventArgs e) {
     224      if (Content == null || Content.EndDate == endDateTimePicker.Value || Content.StartDate == endDateTimePicker.Value) return;
     225
     226      string errorMessage = string.Empty;
     227
     228      var parentProject = HiveAdminClient.Instance.Projects.SingleOrDefault(x => x.Id == Content.ParentProjectId);
     229      if (parentProject != null) {
     230        if (endDateTimePicker.Value > parentProject.EndDate) {
     231          errorMessage = "Project cannot end after its parent project has ended.";
     232        } else if (endDateTimePicker.Value < parentProject.StartDate) {
     233          errorMessage = "Project cannot end before its parent project has started.";
     234        }
     235      }
     236
     237      if (endDateTimePicker.Value < startDateTimePicker.Value) {
     238        errorMessage = "Project cannot end after it starts.";
     239      }
     240
     241      if (!string.IsNullOrEmpty(errorMessage)) {
     242        MessageBox.Show(errorMessage, "HeuristicLab Hive Administrator", MessageBoxButtons.OK, MessageBoxIcon.Error);
     243        endDateTimePicker.Value = Content.EndDate.GetValueOrDefault(Content.StartDate);
     244      }
     245
     246      Content.EndDate = endDateTimePicker.Value;
     247    }
     248
     249    private void indefiniteCheckBox_CheckedChanged(object sender, EventArgs e) {
     250      if (Content == null) return;
     251
     252      var newEndDate = indefiniteCheckBox.Checked ? (DateTime?)null : endDateTimePicker.Value;
     253
     254      if (Content.EndDate == newEndDate) return;
     255      Content.EndDate = newEndDate;
     256
     257      endDateTimePicker.Enabled = !indefiniteCheckBox.Checked;
     258    }
     259
     260    private void AccessClient_Instance_Refreshing(object sender, EventArgs e) {
     261      if (InvokeRequired) {
     262        Invoke((Action<object, EventArgs>)AccessClient_Instance_Refreshing, sender, e);
     263        return;
     264      }
     265
     266      Progress.Show(this, "Refreshing ...", ProgressMode.Indeterminate);
     267      SetEnabledStateOfControls();
     268    }
     269
     270    private void AccessClient_Instance_Refreshed(object sender, EventArgs e) {
     271      if (InvokeRequired) {
     272        Invoke((Action<object, EventArgs>)AccessClient_Instance_Refreshed, sender, e);
     273        return;
     274      }
     275
     276      Progress.Hide(this);
     277      SetEnabledStateOfControls();
     278    }
    309279    #endregion
    310280  }
  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Clients.Hive.JobManager

  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Clients.Hive.JobManager/3.3/Views/HiveJobManagerView.cs

    r17246 r17409  
    144144      if (Content != null && Content.Jobs != null) {
    145145        // clear hive client only if it is not displayed by any other content view (i.e. job manager)
    146         var contentViews = MainFormManager.MainForm.Views.OfType<IContentView>();
    147         if (contentViews.All(x => x.Content != Content || x == this))
     146        var contentViews = MainFormManager.MainForm.Views.OfType<IContentView>()
     147          .Where(v => v.Content == Content && v != this);
     148        if (!contentViews.Any())
    148149          Content.ClearHiveClient();
    149150
  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Clients.Hive.Slave

  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Clients.Hive.Slave/3.3/Manager/ConfigManager.cs

    r17246 r17409  
    2525using System.Linq;
    2626using System.Management;
    27 using System.Net.NetworkInformation;
    2827using HeuristicLab.Clients.Hive.SlaveCore.Properties;
    2928
     
    133132      try {
    134133        prog = jobManager.GetExecutionTimes();
    135       }
    136       catch (Exception ex) {
     134      } catch (Exception ex) {
    137135        SlaveClientCom.Instance.LogMessage(string.Format("Exception was thrown while trying to get execution times: {0}", ex.Message));
    138136      }
     
    140138    }
    141139
     140    /// <summary>
     141    /// Returns the unique machine id of the slave
     142    /// </summary>
     143    /// <returns><see cref="Guid"/></returns>
    142144    public static Guid GetUniqueMachineId() {
    143       Guid id;
    144       try {
    145         id = GetUniqueMachineIdFromMac();
    146       }
    147       catch {
    148         // fallback if something goes wrong...       
    149         id = new Guid(Environment.MachineName.GetHashCode(), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
    150       }
    151       return id;
     145      // Due to the fact that repeated calculation of the machine ID can lead to a client registering at
     146      // the Hive server multiple times with different IDs it's better to set the unique machine id only
     147      // once, at first startup, and store it in core settings.
     148      if (Settings.Default.MachineId == Guid.Empty) {
     149        Settings.Default.MachineId = Guid.NewGuid();
     150        Settings.Default.Save();
     151      }
     152
     153      return Settings.Default.MachineId;
    152154    }
    153155
     
    170172    }
    171173
    172     /// <summary>
    173     /// Generate a guid based on mac address of the first found nic (yes, mac addresses are not unique...)
    174     /// and the machine name.
    175     /// Format:
    176     ///
    177     ///  D1      D2  D3  Res.   D4
    178     /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    179     /// |n a m e|0 0|0 0|0 0 mac address|
    180     /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    181     ///
    182     /// The mac address is saved in the last 48 bits of the Data 4 segment
    183     /// of the guid (first 2 bytes of Data 4 are reserved).
    184     /// D1 contains the hash of the machinename.
    185     /// </summary>   
    186     private static Guid GetUniqueMachineIdFromMac() {
    187       //try to get a real network interface, not a virtual one
    188       NetworkInterface validNic = NetworkInterface.GetAllNetworkInterfaces()
    189                       .FirstOrDefault(x =>
    190                                   !x.Name.Contains(vmwareNameString) &&
    191                                   !x.Name.Contains(virtualboxNameString) &&
    192                                   (x.NetworkInterfaceType == NetworkInterfaceType.Ethernet ||
    193                                    x.NetworkInterfaceType == NetworkInterfaceType.GigabitEthernet));
    194 
    195       if (validNic == default(NetworkInterface)) {
    196         validNic = NetworkInterface.GetAllNetworkInterfaces().First();
    197       }
    198 
    199       byte[] addr = validNic.GetPhysicalAddress().GetAddressBytes();
    200       if (addr.Length < macLength || addr.Length > macLongLength) {
    201         throw new ArgumentException(string.Format("Error generating slave UID: MAC address has to have a length between {0} and {1} bytes. Actual MAC address is: {2}",
    202               macLength, macLongLength, addr));
    203       }
    204 
    205       if (addr.Length < macLongLength) {
    206         byte[] b = new byte[8];
    207         Array.Copy(addr, 0, b, 2, addr.Length);
    208         addr = b;
    209       }
    210 
    211       // also get machine name and save it to the first 4 bytes               
    212       Guid guid = new Guid(Environment.MachineName.GetHashCode(), 0, 0, addr);
    213       return guid;
    214     }
    215 
    216174    private static long? GetWMIValue(string clazz, string property) {
    217175      ManagementClass mgtClass = new ManagementClass(clazz);
     
    223181            try {
    224182              return long.Parse(prop.Value.ToString());
    225             }
    226             catch {
     183            } catch {
    227184              return null;
    228185            }
     
    241198      try {
    242199        mb = (int)(memCounter.NextValue() / 1024 / 1024);
    243       }
    244       catch { }
     200      } catch { }
    245201      return mb;
    246202    }
     
    251207      try {
    252208        return cpuCounter.NextValue();
    253       }
    254       catch { }
     209      } catch { }
    255210      return cpuVal;
    256211    }
  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Clients.Hive.Slave/3.3/Properties/Settings.Designer.cs

    r14164 r17409  
    11//------------------------------------------------------------------------------
    22// <auto-generated>
    3 //     Dieser Code wurde von einem Tool generiert.
    4 //     Laufzeitversion:4.0.30319.42000
     3//     This code was generated by a tool.
     4//     Runtime Version:4.0.30319.42000
    55//
    6 //     Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
    7 //     der Code erneut generiert wird.
     6//     Changes to this file may cause incorrect behavior and will be lost if
     7//     the code is regenerated.
    88// </auto-generated>
    99//------------------------------------------------------------------------------
     
    1313   
    1414    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    15     [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")]
     15    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.2.0.0")]
    1616    public sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
    1717       
     
    323323            }
    324324        }
     325       
     326        [global::System.Configuration.UserScopedSettingAttribute()]
     327        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
     328        [global::System.Configuration.DefaultSettingValueAttribute("00000000-0000-0000-0000-000000000000")]
     329        public global::System.Guid MachineId {
     330            get {
     331                return ((global::System.Guid)(this["MachineId"]));
     332            }
     333            set {
     334                this["MachineId"] = value;
     335            }
     336        }
    325337    }
    326338}
  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Clients.Hive.Slave/3.3/Properties/Settings.settings

    r14164 r17409  
    7878      <Value Profile="(Default)">00:05:00</Value>
    7979    </Setting>
     80    <Setting Name="MachineId" Type="System.Guid" Scope="User">
     81      <Value Profile="(Default)">00000000-0000-0000-0000-000000000000</Value>
     82    </Setting>
    8083  </Settings>
    8184</SettingsFile>
  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Clients.Hive.Slave/3.3/app.config

    r16386 r17409  
    8484      <setting name="CheckpointCheckInterval" serializeAs="String">
    8585        <value>00:05:00</value>
     86      </setting>
     87      <setting name="MachineId" serializeAs="String">
     88        <value>00000000-0000-0000-0000-000000000000</value>
    8689      </setting>
    8790    </HeuristicLab.Clients.Hive.SlaveCore.Properties.Settings>
  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.CodeEditor/3.4/CodeEditor.cs

    r17246 r17409  
    282282    public override void ScrollToPosition(int line, int column) {
    283283      var segment = GetSegmentAtLocation(line, column);
    284       TextEditor.CaretOffset = segment.Offset + segment.Length;
     284      TextEditor.CaretOffset = segment.Offset;
    285285      TextEditor.ScrollToLine(line);
    286286    }
  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Common/3.3/DoubleExtensions.cs

    r17246 r17409  
    2323namespace HeuristicLab.Common {
    2424  public static class DoubleExtensions {
     25    /// <summary>
     26    /// Compares the similarity of value x and value y with a precision of 1.0E-12.
     27    /// </summary>
     28    /// <param name="x">First double value to be checked</param>
     29    /// <param name="y">Second double value to compare with</param>
     30    /// <returns>true if the difference is <= 1.0E-12</returns>
    2531    public static bool IsAlmost(this double x, double y) {
     32      var epsilon = 1.0E-12;
     33      return IsAlmost(x, y, epsilon);
     34    }
     35
     36    /// <summary>
     37    /// Compares the similarity of value x and value y with a given precision (epsilon).
     38    /// </summary>
     39    /// <param name="x">First double value to be checked</param>
     40    /// <param name="y">Second double value to compare with</param>
     41    /// <param name="epsilon">Error term to specify the precision</param>
     42    /// <returns>true if the difference is <= epsilon</returns>
     43    public static bool IsAlmost(this double x, double y, double epsilon) {
    2644      if (double.IsInfinity(x)) {
    2745        if (x > 0) return double.IsPositiveInfinity(y);
    2846        else return double.IsNegativeInfinity(y);
    2947      } else {
    30         return Math.Abs(x - y) < 1.0E-12;
     48        return Math.Abs(x - y) < epsilon;
    3149      }
    3250    }
  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Data

  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Data/3.3

  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Data/3.3/Interfaces/ITextValue.cs

    r17246 r17409  
    2020#endregion
    2121
    22 using System;
    23 using HeuristicLab.Common;
     22using HEAL.Attic;
    2423
    2524namespace HeuristicLab.Data {
    26   public interface ITextValue : IStringConvertibleValue {
    27   }
     25  [StorableType("6fe7970b-66de-4dcf-aa2b-c1aa9d7da29f")]
     26  public interface ITextValue : IStringConvertibleValue { }
    2827}
  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding

  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding-3.4.csproj

    r16662 r17409  
    129129    <Compile Include="ArchitectureManipulators\SubroutineDuplicater.cs" />
    130130    <Compile Include="ArchitectureManipulators\SymbolicExpressionTreeArchitectureManipulator.cs" />
     131    <Compile Include="Creators\BalancedTreeCreator.cs" />
    131132    <Compile Include="Grammars\GrammarUtils.cs" />
    132133    <Compile Include="SymbolicExpressionTreeProblem.cs" />
  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Problems.DataAnalysis

  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Problems.DataAnalysis.Symbolic

  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression.Views

  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression.Views/3.4/InteractiveSymbolicRegressionSolutionSimplifierView.cs

    r17246 r17409  
    3838    }
    3939
     40    protected override void SetEnabledStateOfControls() {
     41      base.SetEnabledStateOfControls();
     42
     43      var tree = Content?.Model?.SymbolicExpressionTree;
     44      btnOptimizeConstants.Enabled = tree != null && SymbolicRegressionConstantOptimizationEvaluator.CanOptimizeConstants(tree);
     45    }
     46
    4047    protected override void UpdateModel(ISymbolicExpressionTree tree) {
    4148      var model = new SymbolicRegressionModel(Content.ProblemData.TargetVariable, tree, Content.Model.Interpreter, Content.Model.LowerEstimationLimit, Content.Model.UpperEstimationLimit);
  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Problems.DataAnalysis.Symbolic.Views

  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Problems.DataAnalysis.Symbolic.Views/3.4/InteractiveSymbolicDataAnalysisSolutionSimplifierView.cs

    r17246 r17409  
    168168    private void Content_Changed(object sender, EventArgs e) {
    169169      UpdateView();
     170      SetEnabledStateOfControls();
    170171    }
    171172
     
    313314    private async void btnOptimizeConstants_Click(object sender, EventArgs e) {
    314315      progress.Start("Optimizing Constants ...");
    315       var tree = (ISymbolicExpressionTree)Content.Model.SymbolicExpressionTree.Clone();
    316       var newTree = await Task.Run(() => OptimizeConstants(tree, progress));
    317       await Task.Delay(500); // wait for progressbar to finish animation
    318       UpdateModel(newTree); // UpdateModel calls Progress.Finish (via Content_Changed)
     316      try {
     317        var tree = (ISymbolicExpressionTree)Content.Model.SymbolicExpressionTree.Clone();
     318        var newTree = await Task.Run(() => OptimizeConstants(tree, progress));
     319        await Task.Delay(500); // wait for progressbar to finish animation
     320        UpdateModel(newTree);
     321      } finally {
     322        progress.Finish();
     323      }
    319324    }
    320325  }
  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/HeuristicLab.Problems.DataAnalysis.Symbolic-3.4.csproj

    r16988 r17409  
    150150    <Compile Include="Converters\DerivativeCalculator.cs" />
    151151    <Compile Include="Converters\TreeToAutoDiffTermConverter.cs" />
     152    <Compile Include="Creators\SymbolicDataAnalysisExpressionBalancedTreeCreator.cs" />
    152153    <Compile Include="Crossovers\SymbolicDataAnalysisExpressionDiversityPreservingCrossover.cs" />
    153154    <Compile Include="Formatters\InfixExpressionFormatter.cs" />
  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Interpreter/SymbolicDataAnalysisExpressionCompiledTreeInterpreter.cs

    r17246 r17409  
    5252    private static readonly MethodInfo Log = typeof(Math).GetMethod("Log", new[] { typeof(double) });
    5353    private static readonly MethodInfo IsNaN = typeof(double).GetMethod("IsNaN");
    54     private static readonly MethodInfo IsAlmost = typeof(DoubleExtensions).GetMethod("IsAlmost");
     54    private static readonly MethodInfo IsAlmost = typeof(DoubleExtensions).GetMethod("IsAlmost", new Type[] { typeof(double), typeof(double)});
    5555    private static readonly MethodInfo Gamma = typeof(alglib).GetMethod("gammafunction", new[] { typeof(double) });
    5656    private static readonly MethodInfo Psi = typeof(alglib).GetMethod("psi", new[] { typeof(double) });
  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Interpreter/SymbolicDataAnalysisExpressionTreeBatchInterpreter.cs

    r16892 r17409  
    1 using System;
     1#region License Information
     2/* HeuristicLab
     3 * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
     4 *
     5 * This file is part of HeuristicLab.
     6 *
     7 * HeuristicLab is free software: you can redistribute it and/or modify
     8 * it under the terms of the GNU General Public License as published by
     9 * the Free Software Foundation, either version 3 of the License, or
     10 * (at your option) any later version.
     11 *
     12 * HeuristicLab is distributed in the hope that it will be useful,
     13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
     14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     15 * GNU General Public License for more details.
     16 *
     17 * You should have received a copy of the GNU General Public License
     18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
     19 */
     20#endregion
     21
     22using System;
    223using System.Collections.Generic;
    324using System.Linq;
     
    181202
    182203    [ThreadStatic]
    183     private Dictionary<string, double[]> cachedData;
     204    private static Dictionary<string, double[]> cachedData;
    184205
    185206    [ThreadStatic]
    186     private IDataset dataset;
     207    private static IDataset cachedDataset;
    187208
    188209    private void InitCache(IDataset dataset) {
    189       this.dataset = dataset;
     210      cachedDataset = dataset;
    190211      cachedData = new Dictionary<string, double[]>();
    191212      foreach (var v in dataset.DoubleVariables) {
     
    196217    public void InitializeState() {
    197218      cachedData = null;
    198       dataset = null;
     219      cachedDataset = null;
    199220      EvaluatedSolutions = 0;
    200221    }
    201222
    202223    private double[] GetValues(ISymbolicExpressionTree tree, IDataset dataset, int[] rows) {
    203       if (cachedData == null || this.dataset != dataset) {
     224      if (cachedData == null || cachedDataset != dataset) {
    204225        InitCache(dataset);
    205226      }
  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Interpreter/SymbolicDataAnalysisExpressionTreeNativeInterpreter.cs

    r17246 r17409  
    9999
    100100    [ThreadStatic]
    101     private IDataset dataset;
     101    private static IDataset cachedDataset;
    102102
    103103    private static readonly HashSet<byte> supportedOpCodes = new HashSet<byte>() {
     
    127127      if (!rows.Any()) return Enumerable.Empty<double>();
    128128
    129       if (cachedData == null || this.dataset != dataset) {
     129      if (cachedData == null || cachedDataset != dataset) {
    130130        InitCache(dataset);
    131131      }
     
    152152
    153153    private void InitCache(IDataset dataset) {
    154       this.dataset = dataset;
     154      cachedDataset = dataset;
    155155
    156156      // free handles to old data
     
    178178        cachedData = null;
    179179      }
    180       dataset = null;
     180      cachedDataset = null;
    181181      EvaluatedSolutions = 0;
    182182    }
  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Problems.DataAnalysis.Views

  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Problems.DataAnalysis.Views/3.4/Classification/ClassificationSolutionVariableImpactsView.Designer.cs

    r17246 r17409  
    192192      this.Name = "ClassificationSolutionVariableImpactsView";
    193193      this.Size = new System.Drawing.Size(712, 365);
    194       this.VisibleChanged += new System.EventHandler(this.ClassificationSolutionVariableImpactsView_VisibleChanged);
    195194      this.ResumeLayout(false);
    196195      this.PerformLayout();
  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Problems.DataAnalysis.Views/3.4/Classification/ClassificationSolutionVariableImpactsView.cs

    r17246 r17409  
    4040    private CancellationTokenSource cancellationToken = new CancellationTokenSource();
    4141    private List<Tuple<string, double>> rawVariableImpacts = new List<Tuple<string, double>>();
     42    private bool attachedToProgress = false;
    4243
    4344    public new IClassificationSolution Content {
     
    8687      }
    8788    }
    88     private void ClassificationSolutionVariableImpactsView_VisibleChanged(object sender, EventArgs e) {
     89    protected override void OnHidden(EventArgs e) {
     90      base.OnHidden(e);
    8991      cancellationToken.Cancel();
     92
     93      if (attachedToProgress) {
     94        Progress.Hide(this);
     95        attachedToProgress = false;
     96      }
    9097    }
    9198
     
    126133      variableImpactsArrayView.Caption = Content.Name + " Variable Impacts";
    127134      progress = Progress.Show(this, "Calculating variable impacts for " + Content.Name);
     135      attachedToProgress = true;
    128136      cancellationToken = new CancellationTokenSource();
    129137
     
    144152        UpdateOrdering();
    145153      } finally {
    146         Progress.Hide(this);
     154        if (attachedToProgress) {
     155          Progress.Hide(this);
     156          attachedToProgress = false;
     157        }
    147158      }
    148159    }
  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionResidualAnalysisView.cs

    r17246 r17409  
    9393      var dateTimeVars = ds.DateTimeVariables.Where(vn => ds.GetDateTimeValues(vn).Distinct().Skip(1).Any()).ToArray();
    9494
    95       // produce training and test values separately as they might overlap (e.g. for ensembles)
    96       var predictedValuesTrain = Content.EstimatedTrainingValues.ToArray();
    97       int j = 0; // idx for predictedValues array
    98       foreach (var i in problemData.TrainingIndices) {
     95      var predictedValues = Content.EstimatedValues.ToArray();
     96      foreach (var i in problemData.AllIndices) {
    9997        var run = CreateRunForIdx(i, problemData, doubleVars, stringVars, dateTimeVars);
    10098        var targetValue = ds.GetDoubleValue(problemData.TargetVariable, i);
    101         AddErrors(run, predictedValuesTrain[j++], targetValue);
    102         run.Results.Add(PartitionLabel, new StringValue("Training"));
    103         run.Color = Color.Gold;
     99        AddErrors(run, predictedValues[i], targetValue);
     100
     101        if (problemData.IsTrainingSample(i) && problemData.IsTestSample(i)) {
     102          run.Results.Add(PartitionLabel, new StringValue("Training + Test"));
     103          run.Color = Color.Orange;
     104        } else if (problemData.IsTrainingSample(i)) {
     105          run.Results.Add(PartitionLabel, new StringValue("Training"));
     106          run.Color = Color.Gold;
     107        } else if (problemData.IsTestSample(i)) {
     108          run.Results.Add(PartitionLabel, new StringValue("Test"));
     109          run.Color = Color.Red;
     110        } else {
     111          run.Results.Add(PartitionLabel, new StringValue("Additional Data"));
     112          run.Color = Color.Black;
     113        }
    104114        runs.Add(run);
    105115      }
    106       var predictedValuesTest = Content.EstimatedTestValues.ToArray();
    107       j = 0;
    108       foreach (var i in problemData.TestIndices) {
    109         var run = CreateRunForIdx(i, problemData, doubleVars, stringVars, dateTimeVars);
    110         var targetValue = ds.GetDoubleValue(problemData.TargetVariable, i);
    111         AddErrors(run, predictedValuesTest[j++], targetValue);
    112         run.Results.Add(PartitionLabel, new StringValue("Test"));
    113         run.Color = Color.Red;
    114         runs.Add(run);
    115       }
     116
    116117      if (string.IsNullOrEmpty(selectedXAxis))
    117118        selectedXAxis = "Index";
  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionVariableImpactsView.Designer.cs

    r17246 r17409  
    192192      this.Name = "RegressionSolutionVariableImpactsView";
    193193      this.Size = new System.Drawing.Size(712, 365);
    194       this.VisibleChanged += new System.EventHandler(this.RegressionSolutionVariableImpactsView_VisibleChanged);
    195194      this.ResumeLayout(false);
    196195      this.PerformLayout();
  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionVariableImpactsView.cs

    r17246 r17409  
    4040    private CancellationTokenSource cancellationToken = new CancellationTokenSource();
    4141    private List<Tuple<string, double>> rawVariableImpacts = new List<Tuple<string, double>>();
     42    private bool attachedToProgress = false;
    4243
    4344    public new IRegressionSolution Content {
     
    8687      }
    8788    }
    88     private void RegressionSolutionVariableImpactsView_VisibleChanged(object sender, EventArgs e) {
     89
     90    protected override void OnHidden(EventArgs e) {
     91      base.OnHidden(e);
    8992      cancellationToken.Cancel();
     93
     94      if (attachedToProgress) {
     95        Progress.Hide(this);
     96        attachedToProgress = false;
     97      }
    9098    }
    9199
     
    124132      variableImpactsArrayView.Caption = Content.Name + " Variable Impacts";
    125133      var progress = Progress.Show(this, "Calculating variable impacts for " + Content.Name);
     134      attachedToProgress = true;
    126135      cancellationToken = new CancellationTokenSource();
    127136
     
    141150        rawVariableImpacts.AddRange(impacts);
    142151        UpdateOrdering();
    143       }
    144       finally {
    145         Progress.Hide(this);
     152      } finally {
     153        if (attachedToProgress) {
     154          Progress.Hide(this);
     155          attachedToProgress = false;
     156        }
    146157      }
    147158    }
  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Problems.DataAnalysis/3.4

  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Interval.cs

    r17246 r17409  
    3737    protected Interval(StorableConstructorFlag _) { }
    3838
     39    /// <summary>
     40    /// Creates an interval with given bounds, where lower bound must be smaller than
     41    /// the upper bound. Floating point precision errors trough calculations are fixed by,
     42    /// checking if the intervals are almost the same (E-12). If this is the case, the bounds
     43    /// will be set to the bound closer to zero.
     44    /// </summary>
     45    /// <param name="lowerBound">Lower bound of the interval</param>
     46    /// <param name="upperBound">Upper bound of the interval</param>
    3947    public Interval(double lowerBound, double upperBound) {
     48      if (lowerBound.IsAlmost(upperBound)) {
     49        //If the bounds go over zero
     50        if (lowerBound <= 0 && upperBound >= 0) {
     51          lowerBound = 0.0;
     52          upperBound = 0.0;
     53          //Interval is negative
     54        } else if (upperBound < 0) {
     55          lowerBound = upperBound;
     56          //Interval is positive
     57        } else {
     58          upperBound = lowerBound;
     59        }
     60      }
     61
    4062      if (lowerBound > upperBound)
    4163        throw new ArgumentException("LowerBound must be smaller than UpperBound.");
     
    5880                double.IsNaN(LowerBound) || double.IsNaN(UpperBound);
    5981      }
     82    }
     83
     84    /// <summary>
     85    /// True if the interval is positive without zero
     86    /// </summary>
     87    public bool IsPositive {
     88      get => LowerBound > 0.0;
     89    }
     90
     91    /// <summary>
     92    /// True if the interval is negative without zero
     93    /// </summary>
     94    public bool IsNegative {
     95      get => UpperBound < 0.0;
    6096    }
    6197
     
    128164    }
    129165
    130     //mkommend: Division by intervals containing 0 is implemented as defined in
     166    //Division by intervals containing 0 is implemented as defined in
    131167    //http://en.wikipedia.org/wiki/Interval_arithmetic
    132168    public static Interval Divide(Interval a, Interval b) {
     
    171207    public static Interval Tangens(Interval a) {
    172208      return Interval.Divide(Interval.Sine(a), Interval.Cosine(a));
    173     } 
     209    }
    174210    public static Interval HyperbolicTangent(Interval a) {
    175211      return new Interval(Math.Tanh(a.LowerBound), Math.Tanh(a.UpperBound));
     
    226262
    227263    public static Interval CubicRoot(Interval a) {
    228       if (a.LowerBound < 0) return new Interval(double.NaN, double.NaN);
    229       return new Interval(Math.Pow(a.LowerBound, 1.0 / 3), Math.Pow(a.UpperBound, 1.0 / 3));
     264      var lower = (a.LowerBound < 0) ? -Math.Pow(-a.LowerBound, 1d / 3d) : Math.Pow(a.LowerBound, 1d / 3d);
     265      var upper = (a.UpperBound < 0) ? -Math.Pow(-a.UpperBound, 1d / 3d) : Math.Pow(a.UpperBound, 1d / 3d);
     266
     267      return new Interval(lower, upper);
     268    }
     269
     270    public static Interval Absolute(Interval a) {
     271      var absLower = Math.Abs(a.LowerBound);
     272      var absUpper = Math.Abs(a.UpperBound);
     273      var min = Math.Min(absLower, absUpper);
     274      var max = Math.Max(absLower, absUpper);
     275
     276      if (a.Contains(0.0)) {
     277        min = 0.0;
     278      }
     279
     280      return new Interval(min, max);
     281    }
     282
     283    public static Interval AnalyticalQuotient(Interval a, Interval b) {
     284      var dividend = a;
     285      var divisor = Add(Square(b), new Interval(1.0, 1.0));
     286      divisor = SquareRoot(divisor);
     287
     288      var quotient = Divide(dividend, divisor);
     289      return quotient;
    230290    }
    231291    #endregion
  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Scripting.Views/3.3/HeuristicLab.Scripting.Views-3.3.csproj

    r16662 r17409  
    9797    <Compile Include="CSharpScriptView.Designer.cs">
    9898      <DependentUpon>CSharpScriptView.cs</DependentUpon>
     99    </Compile>
     100    <Compile Include="CompilerErrorDialog.cs">
     101      <SubType>Form</SubType>
     102    </Compile>
     103    <Compile Include="CompilerErrorDialog.Designer.cs">
     104      <DependentUpon>CompilerErrorDialog.cs</DependentUpon>
    99105    </Compile>
    100106    <Compile Include="ExecutableScriptView.cs">
  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Scripting.Views/3.3/ScriptView.Designer.cs

    r17246 r17409  
    184184      this.errorListView.UseCompatibleStateImageBehavior = false;
    185185      this.errorListView.View = System.Windows.Forms.View.Details;
     186      this.errorListView.MouseClick += new System.Windows.Forms.MouseEventHandler(this.errorListView_MouseClick);
    186187      this.errorListView.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.errorListView_MouseDoubleClick);
    187188      //
  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Scripting.Views/3.3/ScriptView.cs

    r17246 r17409  
    209209    }
    210210
     211    private void errorListView_MouseClick(object sender, MouseEventArgs e) {
     212      if (e.Button != MouseButtons.Left) return;
     213
     214      var item = errorListView.SelectedItems[0];
     215      var message = (CompilerError)item.Tag;
     216
     217      codeEditor.ScrollToPosition(message.Line, message.Column);
     218      codeEditor.Focus();
     219    }
     220
    211221    private void errorListView_MouseDoubleClick(object sender, MouseEventArgs e) {
    212       if (e.Button == MouseButtons.Left) {
    213         var item = errorListView.SelectedItems[0];
    214         var message = (CompilerError)item.Tag;
    215         codeEditor.ScrollToPosition(message.Line, message.Column);
    216         codeEditor.Focus();
    217       }
     222      if (e.Button != MouseButtons.Left) return;
     223
     224      var item = errorListView.SelectedItems[0];
     225      var message = (CompilerError)item.Tag;
     226
     227      using (var dialog = new CompilerErrorDialog(message)) {
     228        dialog.ShowDialog(this);
     229      };
    218230    }
    219231    #endregion
  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Scripting/3.3/Script.cs

    r17246 r17409  
    4040  public abstract class Script : NamedItem, IProgrammableItem {
    4141    #region Fields & Properties
     42    public static readonly HashSet<string> ExcludedAssemblyFileNames = new HashSet<string> { "IKVM.OpenJDK.ClassLibrary.dll" };
    4243    public static new Image StaticItemImage {
    4344      get { return VSImageLibrary.Script; }
     
    124125    public virtual IEnumerable<Assembly> GetAssemblies() {
    125126      var assemblies = AppDomain.CurrentDomain.GetAssemblies()
    126         .Where(a => !a.IsDynamic && File.Exists(a.Location))
     127        .Where(a => !a.IsDynamic && File.Exists(a.Location)
     128                 && !ExcludedAssemblyFileNames.Contains(Path.GetFileName(a.Location)))
    127129        .GroupBy(x => Regex.Replace(Path.GetFileName(x.Location), @"-[\d.]+\.dll$", ""))
    128130        .Select(x => x.OrderByDescending(y => y.GetName().Version).First())
  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Services.Hive

  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Services.Hive/3.3/HiveService.cs

    r17246 r17409  
    665665            bool oldIsAllowedToCalculate = slave.IsAllowedToCalculate;
    666666            Guid? oldParentResourceId = slave.ParentResourceId;
     667            bool? oldIsDisposable = slave.IsDisposable;
    667668            slaveInfo.CopyToEntity(slave);
    668669            slave.IsAllowedToCalculate = oldIsAllowedToCalculate;
    669670            slave.ParentResourceId = oldParentResourceId;
     671            slave.IsDisposable = oldIsDisposable;
    670672            slave.LastHeartbeat = DateTime.Now;
    671673            slave.SlaveState = DA.SlaveState.Idle;
  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Tests

  • branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Tests/HeuristicLab.Problems.DataAnalysis-3.4/IntervalTest.cs

    r16662 r17409  
    1414    [TestCategory("Problems.DataAnalysis")]
    1515    [TestProperty("Time", "short")]
    16     public void TestIntervalAddOperation() {
     16    public void AddIntervalTest() {
    1717      //add        [x1,x2] + [y1,y2] = [x1 + y1,x2 + y2]
    1818
     
    2828    [TestCategory("Problems.DataAnalysis")]
    2929    [TestProperty("Time", "short")]
    30     public void TestIntervalSubOperation() {
     30    public void SubtractIntervalTest() {
    3131      //subtract   [x1,x2] − [y1,y2] = [x1 − y2,x2 − y1]
    3232
     
    4242    [TestCategory("Problems.DataAnalysis")]
    4343    [TestProperty("Time", "short")]
    44     public void TestIntervalMutlipyOperation() {
     44    public void MultiplyIntervalTest() {
    4545      //multiply   [x1,x2] * [y1,y2] = [min(x1*y1,x1*y2,x2*y1,x2*y2),max(x1*y1,x1*y2,x2*y1,x2*y2)]
    4646
     
    5959    [TestCategory("Problems.DataAnalysis")]
    6060    [TestProperty("Time", "short")]
    61     public void TestIntervalDivideOperation() {
     61    public void DivideIntervalTest() {
    6262      //divide  [x1, x2] / [y1, y2] = [x1, x2] * (1/[y1, y2]), where 1 / [y1,y2] = [1 / y2,1 / y1] if 0 not in [y_1, y_2].
    6363
     
    8080    [TestCategory("Problems.DataAnalysis")]
    8181    [TestProperty("Time", "short")]
    82     public void TestIntervalSineOperator() {
     82    public void SineIntervalTest() {
    8383      //sine depends on interval
    8484      //sin([0, 2*pi]) = [-1, 1]
     
    9898    [TestCategory("Problems.DataAnalysis")]
    9999    [TestProperty("Time", "short")]
    100     public void TestIntervalCosineOperator() {
     100    public void CosineIntervalTest() {
    101101      //Cosine uses sine Interval.Sine(Interval.Subtract(a, new Interval(Math.PI / 2, Math.PI / 2)));
    102102      Assert.AreEqual<Interval>(Interval.Cosine(new Interval(0, 2 * Math.PI)), new Interval(-1, 1));
     
    107107    [TestCategory("Problems.DataAnalysis")]
    108108    [TestProperty("Time", "short")]
    109     public void TestIntervalLogOperator() {
     109    public void LogIntervalTest() {
    110110      //Log([3, 5]) = [log(3), log(5)]
    111111      Assert.AreEqual<Interval>(new Interval(Math.Log(3), Math.Log(5)), Interval.Logarithm(new Interval(3, 5)));
     
    122122    [TestCategory("Problems.DataAnalysis")]
    123123    [TestProperty("Time", "short")]
    124     public void TestIntervalExpOperator() {
     124    public void ExponentialIntervalTest() {
    125125      //Exp([0, 1]) = [exp(0), exp(1)]
    126126      Assert.AreEqual<Interval>(new Interval(1, Math.Exp(1)), Interval.Exponential(new Interval(0, 1)));
     
    131131    [TestCategory("Problems.DataAnalysis")]
    132132    [TestProperty("Time", "short")]
    133     public void TestIntervalSqrOperator() {
     133    public void SquareIntervalTest() {
    134134      Assert.AreEqual<Interval>(new Interval(1, 4), Interval.Square(new Interval(1, 2)));
    135135      Assert.AreEqual<Interval>(new Interval(1, 4), Interval.Square(new Interval(-2, -1)));
     
    140140    [TestCategory("Problems.DataAnalysis")]
    141141    [TestProperty("Time", "short")]
    142     public void TestIntervalSqrtOperator() {
     142    public void SquarerootIntervalTest() {
    143143      Assert.AreEqual<Interval>(new Interval(1, 2), Interval.SquareRoot(new Interval(1, 4)));
    144144      Assert.AreEqual<Interval>(new Interval(double.NaN, double.NaN), Interval.SquareRoot(new Interval(-4, -1)));
     
    148148    [TestCategory("Problems.DataAnalysis")]
    149149    [TestProperty("Time", "short")]
    150     public void TestIntervalCubeOperator() {
     150    public void CubeIntervalTest() {
    151151      Assert.AreEqual<Interval>(new Interval(1, 8), Interval.Cube(new Interval(1, 2)));
    152152      Assert.AreEqual<Interval>(new Interval(-8, -1), Interval.Cube(new Interval(-2, -1)));
     
    157157    [TestCategory("Problems.DataAnalysis")]
    158158    [TestProperty("Time", "short")]
    159     public void TestIntervalCbrtOperator() {
     159    public void CubeRootIntervalTest() {
    160160      Assert.AreEqual<Interval>(new Interval(1, 2), Interval.CubicRoot(new Interval(1, 8)));
    161       Assert.AreEqual<Interval>(new Interval(double.NaN, double.NaN), Interval.CubicRoot(new Interval(-8, -1)));
     161      Assert.AreEqual<Interval>(new Interval(-2, -2), Interval.CubicRoot(new Interval(-8, -8)));
     162      Assert.AreEqual<Interval>(new Interval(-2, 2), Interval.CubicRoot(new Interval(-8, 8)));
     163      Assert.AreEqual(new Interval(2, 2), Interval.CubicRoot(new Interval(8, 8)));
     164      Assert.AreEqual(new Interval(-Math.Pow(6, 1.0 / 3), 2), Interval.CubicRoot(new Interval(-6, 8)));
     165      Assert.AreEqual(new Interval(2, 2), Interval.CubicRoot(new Interval(8, 8)));
     166      Assert.AreEqual(new Interval(-2, 0), Interval.CubicRoot(new Interval(-8, 0)));
     167    }
     168
     169    [TestMethod]
     170    [TestCategory("Problems.DataAnalysis")]
     171    [TestProperty("Time", "short")]
     172    public void AbsoluteIntervalTest() {
     173      Assert.AreEqual(new Interval(2, 5), Interval.Absolute(new Interval(-5, -2)));
     174      Assert.AreEqual(new Interval(2, 5), Interval.Absolute(new Interval(2, 5)));
     175      Assert.AreEqual(new Interval(0, 3), Interval.Absolute(new Interval(-3, 0)));
     176      Assert.AreEqual(new Interval(0, 5), Interval.Absolute(new Interval(0, 5)));
     177      Assert.AreEqual(new Interval(0, 5), Interval.Absolute(new Interval(-2, 5)));
     178    }
     179
     180    [TestMethod]
     181    [TestCategory("Problems.DataAnalysis")]
     182    [TestProperty("Time", "short")]
     183    public void AnalyticalQuotientIntervalTest() {
     184      //Analytical Quotient ==> a / sqrt(b^2 + 1)
     185      var aPos = new Interval(3, 5);
     186      var aZero = new Interval(-3, 5);
     187      var aNeg = new Interval(-5, -3);
     188
     189      var bPos = new Interval(2, 4);
     190      var bZero = new Interval(-2, 4);
     191      var bNeg = new Interval(-4, -2);
     192
     193      //Second interval goes over zero
     194      Assert.AreEqual(new Interval(aPos.LowerBound/Math.Sqrt(17), aPos.UpperBound), Interval.AnalyticalQuotient(aPos, bZero));
     195      Assert.AreEqual(new Interval(aZero.LowerBound, aZero.UpperBound), Interval.AnalyticalQuotient(aZero, bZero));
     196      Assert.AreEqual(new Interval(aNeg.LowerBound, aNeg.UpperBound/Math.Sqrt(17)), Interval.AnalyticalQuotient(aNeg, bZero));
     197      //Second interval is positive
     198      Assert.AreEqual(new Interval(aPos.LowerBound/Math.Sqrt(17), aPos.UpperBound/Math.Sqrt(5)), Interval.AnalyticalQuotient(aPos, bPos));
     199      Assert.AreEqual(new Interval(aZero.LowerBound/Math.Sqrt(5), aZero.UpperBound/Math.Sqrt(5)), Interval.AnalyticalQuotient(aZero, bPos));
     200      Assert.AreEqual(new Interval(aNeg.LowerBound/Math.Sqrt(5), aNeg.UpperBound/Math.Sqrt(17)), Interval.AnalyticalQuotient(aNeg, bPos));
     201      //Second interval is negative
     202      Assert.AreEqual(new Interval(aPos.LowerBound/Math.Sqrt(17), aPos.UpperBound/Math.Sqrt(5)), Interval.AnalyticalQuotient(aPos, bNeg));
     203      Assert.AreEqual(new Interval(aZero.LowerBound/Math.Sqrt(5), aZero.UpperBound/Math.Sqrt(5)), Interval.AnalyticalQuotient(aZero, bNeg));
     204      Assert.AreEqual(new Interval(aNeg.LowerBound/Math.Sqrt(5), aNeg.UpperBound/Math.Sqrt(17)), Interval.AnalyticalQuotient(aNeg, bNeg));
     205    }
     206
     207    [TestMethod]
     208    [TestCategory("Problems.DataAnalysis")]
     209    [TestProperty("Time", "short")]
     210    public void IsNegativeIntervalTest() {
     211      Assert.IsTrue(new Interval(-2, -1).IsNegative);
     212      Assert.IsFalse(new Interval(-2, 0).IsNegative);
     213      Assert.IsFalse(new Interval(-2, 2).IsNegative);
     214      Assert.IsFalse(new Interval(2, 4).IsNegative);
     215    }
     216
     217    [TestMethod]
     218    [TestCategory("Problems.DataAnalysis")]
     219    [TestProperty("Time", "short")]
     220    public void IsPositiveIntervalTest() {
     221      Assert.IsTrue(new Interval(3, 5).IsPositive);
     222      Assert.IsFalse(new Interval(0, 5).IsPositive);
     223      Assert.IsFalse(new Interval(-1, 5).IsPositive);
     224      Assert.IsFalse(new Interval(-5, -2).IsPositive);
     225    }
     226
     227    [TestMethod]
     228    [TestCategory("Problems.DataAnalysis")]
     229    [TestProperty("Time", "short")]
     230    public void IsAlmostIntervalTest() {
     231      var negativeLowerBound = -2E-13;
     232      var negativeUpperBound = -1E-13;
     233      var positiveLowerBound = 3E-13;
     234      var positiveUpperBound = 5E-13;
     235
     236      var negativeInterval = new Interval(negativeLowerBound, negativeUpperBound);
     237      var positiveInterval = new Interval(positiveLowerBound, positiveUpperBound);
     238      var zeroInterval = new Interval(negativeUpperBound, positiveLowerBound);
     239
     240      //Check for right-shift of negative interval
     241      Assert.AreEqual(negativeUpperBound, negativeInterval.LowerBound);
     242      Assert.AreEqual(negativeUpperBound, negativeInterval.UpperBound);
     243      //Check for left-shift of positive interval
     244      Assert.AreEqual(positiveLowerBound, positiveInterval.LowerBound);
     245      Assert.AreEqual(positiveLowerBound, positiveInterval.UpperBound);
     246      //Check for setting interval to zero
     247      Assert.AreEqual(0, zeroInterval.LowerBound);
     248      Assert.AreEqual(0, zeroInterval.UpperBound);
     249
    162250    }
    163251  }
Note: See TracChangeset for help on using the changeset viewer.