Business Objects & Instantiation
Visualization
The image below visualizes the data created below. For this example we have 8 different Items "A"-"H" with their according weight (upper number) and value (lower number).
Item (Business Object)
The Business Objects for the Knapsack Problem are items with a weight and value.
KnapsackItem.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Knapsack
{
/// <summary>
/// creates an item for the Knapsack Problem
/// </summary>
public class KnapsackItem
{
/// <summary>
/// the weight of the item
/// </summary>
public double Weight { get; set; }
/// <summary>
/// the value of the item
/// </summary>
public double Value { get; set; }
public string Name { get; set; }
public bool IsPacked { get; set; }
public override string ToString() => Name;
}
}
Program instance
Instantiation of Business Objects, the Model, as well as the Solver and an empty Solution.
Program.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CsvHelper;
namespace Knapsack
{
using OPTANO.Modeling.Common;
using OPTANO.Modeling.Optimization;
using OPTANO.Modeling.Optimization.Configuration;
using OPTANO.Modeling.Optimization.Solver.Gurobi810;
/// <summary>
/// Demo program solving a Knapsack Problem
/// </summary>
class Program
{
/// <summary>
/// The main method
/// </summary>
/// <param name="args">
/// no arguments required
/// </param>
static void Main(string[] args)
{
// create example Items
var csv = new CsvReader(File.OpenText("knapsackItems.csv"));
csv.Configuration.Delimiter = ";";
csv.Configuration.CultureInfo = new CultureInfo("en-US");
csv.Configuration.RegisterClassMap<KnapsackItemMap>();
var items = csv.GetRecords<KnapsackItem>().ToList();
// maximum weight of all the items
var maxWeight = 10.8;
// Use long names for easier debugging/model understanding.
var config = new Configuration
{
NameHandling = NameHandlingStyle.UniqueLongNames,
ComputeRemovedVariables = true
};
using (var scope = new ModelScope(config))
{
// create a model, based on given data and the model scope
var knapsackModel = new KnapsackModel(items, maxWeight);
// Get a solver instance, change your solver
using (var solver = new GurobiSolver())
{
// solve the model
var solution = solver.Solve(knapsackModel.Model);
// import the results back into the model
knapsackModel.Model.VariableCollections.ForEach(vc => vc.SetVariableValues(solution.VariableValues));
// print objective and variable decisions
Console.WriteLine($"{solution.ObjectiveValues.Single()}");
knapsackModel.y.Variables.ForEach(y => Console.WriteLine($"{y.ToString().PadRight(36)}: {y.Value}"));
knapsackModel.Model.VariableStatistics.WriteCSV(AppDomain.CurrentDomain.BaseDirectory);
Console.ReadLine();
}
}
}
}
}
Next Step
- Creating the Model