Free cookie consent management tool by TermsFeed Policy Generator

source: branches/3082_Scaling/HeuristicLab.ExactOptimization/3.3/LinearProgramming/Problems/ProgrammableLinearProblemDefinition.cs @ 17915

Last change on this file since 17915 was 17180, checked in by swagner, 5 years ago

#2875: Removed years in copyrights

File size: 5.9 KB
Line 
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;
23using System.Linq;
24using System.Reflection;
25using Google.OrTools.LinearSolver;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.ExactOptimization.LinearProgramming.Templates;
29using HeuristicLab.Optimization;
30using HeuristicLab.Problems.Programmable;
31using HeuristicLab.Scripting;
32using HEAL.Attic;
33
34namespace HeuristicLab.ExactOptimization.LinearProgramming {
35
36  [Item("Programmable Linear Problem Definition (LP, MIP)",
37    "Script that defines the model for a linear/mixed integer programming problem.")]
38  [StorableType("830F82CF-9FF1-4619-A75E-E43E208565F0")]
39  public sealed class ProgrammableLinearProblemDefinition : Script, ILinearProblemDefinition,
40    IStorableContent {
41    private readonly object compileLock = new object();
42
43    [Storable]
44    private readonly VariableStore variableStore;
45
46    [Storable]
47    private bool codeChanged;
48
49    private volatile ILinearProblemDefinition compiledProblemDefinition;
50
51    public ProgrammableLinearProblemDefinition()
52      : base(ScriptTemplates.CompiledLinearProblemDefinition) {
53      Name = "Programmable Linear Problem Definition";
54      variableStore = new VariableStore();
55    }
56
57    [StorableConstructor]
58    private ProgrammableLinearProblemDefinition(StorableConstructorFlag _) : base(_) { }
59
60    private ProgrammableLinearProblemDefinition(ProgrammableLinearProblemDefinition original,
61      Cloner cloner) : base(original, cloner) {
62      variableStore = cloner.Clone(original.variableStore);
63      codeChanged = original.codeChanged;
64    }
65
66    public event EventHandler ProblemDefinitionChanged;
67
68    public string Filename { get; set; }
69    public dynamic Instance => compiledProblemDefinition;
70    public VariableStore VariableStore => variableStore;
71
72    private ILinearProblemDefinition CompiledProblemDefinition {
73      get {
74        // double checked locking pattern
75        if (compiledProblemDefinition == null) {
76          lock (compileLock) {
77            if (compiledProblemDefinition == null) {
78              if (codeChanged)
79                throw new ProblemDefinitionScriptException("The code has been changed, but was not recompiled.");
80              Compile(false);
81            }
82          }
83        }
84
85        return compiledProblemDefinition;
86      }
87    }
88
89    public void Analyze(Solver solver, ResultCollection results) => CompiledProblemDefinition.Analyze(solver, results);
90
91    public void BuildModel(Solver solver) => CompiledProblemDefinition.BuildModel(solver);
92
93    public override IDeepCloneable Clone(Cloner cloner) {
94      return new ProgrammableLinearProblemDefinition(this, cloner);
95    }
96
97    public override Assembly Compile() => Compile(true);
98
99    protected override void OnCodeChanged() {
100      base.OnCodeChanged();
101      compiledProblemDefinition = null;
102      codeChanged = true;
103    }
104
105    private Assembly Compile(bool fireChanged) {
106      var assembly = base.Compile();
107      var types = assembly.GetTypes();
108      if (!types.Any(x => typeof(CompiledProblemDefinition).IsAssignableFrom(x)))
109        throw new ProblemDefinitionScriptException("The compiled code doesn't contain a problem definition." + Environment.NewLine +
110                                                   $"The problem definition must be a subclass of {nameof(CompiledProblemDefinition)} and implement {nameof(ILinearProblemDefinition)}.");
111      if (types.Count(x => typeof(CompiledProblemDefinition).IsAssignableFrom(x)) > 1)
112        throw new ProblemDefinitionScriptException("The compiled code contains multiple problem definitions." + Environment.NewLine +
113                                                   $"Only one subclass of {nameof(CompiledProblemDefinition)} is allowed.");
114
115      CompiledProblemDefinition inst;
116      try {
117        inst = (CompiledProblemDefinition)Activator.CreateInstance(types.Single(x =>
118         typeof(CompiledProblemDefinition).IsAssignableFrom(x)));
119      } catch (Exception e) {
120        compiledProblemDefinition = null;
121        throw new ProblemDefinitionScriptException(
122          "Instantiating the problem definition failed." + Environment.NewLine + "Check your default constructor.", e);
123      }
124
125      try {
126        inst.vars = new Variables(VariableStore);
127        inst.Initialize();
128      } catch (Exception e) {
129        compiledProblemDefinition = null;
130        throw new ProblemDefinitionScriptException(
131          "Initializing the problem definition failed." + Environment.NewLine + "Check your Initialize() method.", e);
132      }
133
134      try {
135        compiledProblemDefinition = (ILinearProblemDefinition)inst;
136        if (fireChanged) OnProblemDefinitionChanged();
137      } catch (Exception e) {
138        compiledProblemDefinition = null;
139        throw new ProblemDefinitionScriptException(
140          "Using the problem definition in the problem failed." + Environment.NewLine +
141          "Examine this error message carefully.", e);
142      }
143
144      codeChanged = false;
145      return assembly;
146    }
147
148    private void OnProblemDefinitionChanged() => ProblemDefinitionChanged?.Invoke(this, EventArgs.Empty);
149  }
150}
Note: See TracBrowser for help on using the repository browser.