Skip to content

Commit

Permalink
Finished first homework.
Browse files Browse the repository at this point in the history
  • Loading branch information
ojanacek committed Oct 21, 2015
1 parent 1643330 commit cb643a2
Show file tree
Hide file tree
Showing 12 changed files with 468 additions and 128 deletions.
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,53 +1,59 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{F1874205-A569-4348-9791-898A2F161DEF}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>KnapsackProblem.BruteForce</RootNamespace>
<AssemblyName>KnapsackProblem.BruteForce</AssemblyName>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{F1874205-A569-4348-9791-898A2F161DEF}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>KnapsackProblem.BFvsHeuristics</RootNamespace>
<AssemblyName>KnapsackProblem.BFvsHeuristics</AssemblyName>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\KnapsackProblem.Common\KnapsackProblem.Common.csproj">
<Project>{d69e0ecc-70c5-41c3-abba-e4f385e6982a}</Project>
<Name>KnapsackProblem.Common</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
-->
</Project>
175 changes: 175 additions & 0 deletions KnapsackProblem.BFvsHeuristics/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using KnapsackProblem.Common;

namespace KnapsackProblem.BFvsHeuristics
{
class Program
{
static void Main(string[] args)
{
if (args.Length == 0)
{
Console.WriteLine("No path provided.");
return;
}

MeasureRelativeErrors(args[0]);
}

/// <summary> Generate file with results to check against referece results. </summary>
static void SaveResultsForCheck(string filePath)
{
if (!File.Exists(filePath))
{
Console.WriteLine("File '{0}' does not exist.", filePath);
return;
}

var sb = new StringBuilder();
foreach (var knapsack in KnapsackLoader.LoadKnapsacks(filePath, 500))
{
//var result = KnapsackProblemSolver.BruteForce(knapsack);
var result = KnapsackProblemSolver.PriceToWeightRatioHeuristics(knapsack);
sb.AppendLine($"{knapsack.Id} {knapsack.InstanceSize} {result.Item1} {result.Item2.ToReverseBinary(knapsack.InstanceSize)}");
}

File.WriteAllText("result.txt", sb.ToString());
}

static void MeasureBFTimePerInstanceSize(string directoryPath, int knapsacksPerInstanceSize, TimeSpan maxTimePerInstance)
{
if (!Directory.Exists(directoryPath))
{
Console.WriteLine("Directory '{0}' does not exist.", directoryPath);
return;
}

var knapsacksFiles = Directory.EnumerateFiles(directoryPath, "knap_*.dat").Where(f => !f.Contains("sol")).ToList();

// warmup
foreach (var knapsack in KnapsackLoader.LoadKnapsacks(knapsacksFiles.First(), 50))
{
var result = KnapsackProblemSolver.BruteForce(knapsack);
Console.WriteLine(result); // so that it's not optimized away
}
GC.Collect();

// measure
var bfWatch = new Stopwatch();
int originalKnapsacksPerInstanceSize = knapsacksPerInstanceSize;

for (int i = 0; i < knapsacksFiles.Count; i++)
{
string file = knapsacksFiles[i];
int instanceSize = 0;

Console.WriteLine("Starting {0}", file);
int j = 0;

foreach (var knapsack in KnapsackLoader.LoadKnapsacks(file, knapsacksPerInstanceSize))
{
instanceSize = knapsack.InstanceSize;
bfWatch.Start();
KnapsackProblemSolver.BruteForce(knapsack);
bfWatch.Stop();
Console.WriteLine("--finished {0}: {1}", j, bfWatch.ElapsedMilliseconds);
}

double instanceAverage = bfWatch.ElapsedMilliseconds / (double)knapsacksPerInstanceSize;
if (Math.Abs(instanceAverage) < 0.0000001)
{
i--;
knapsacksPerInstanceSize = 500;
continue;
}

File.Create($"{instanceSize};{instanceAverage}.txt");

knapsacksPerInstanceSize = originalKnapsacksPerInstanceSize;
bfWatch.Reset();
GC.Collect();
if (instanceAverage > maxTimePerInstance.TotalMilliseconds)
break;
}
}

static void MeasureHeuristicsTimePerInstanceSize(string directoryPath)
{
if (!Directory.Exists(directoryPath))
{
Console.WriteLine("Directory '{0}' does not exist.", directoryPath);
return;
}

var knapsacksFiles = Directory.EnumerateFiles(directoryPath, "knap_*.dat").Where(f => !f.Contains("sol")).ToList();

// warmup
foreach (var knapsack in KnapsackLoader.LoadKnapsacks(knapsacksFiles.First(), 500))
{
var result = KnapsackProblemSolver.PriceToWeightRatioHeuristics(knapsack);
Console.WriteLine(result); // so that it's not optimized away
}
GC.Collect();

// measure
var bfWatch = new Stopwatch();
var repeat = 50;

foreach (string file in knapsacksFiles)
{
int instanceSize = 0;
for (int i = 0; i < repeat; i++)
{
foreach (var knapsack in KnapsackLoader.LoadKnapsacks(file, 500))
{
instanceSize = knapsack.InstanceSize;
bfWatch.Start();
KnapsackProblemSolver.PriceToWeightRatioHeuristics(knapsack);
bfWatch.Stop();
}
}

double instanceAverage = bfWatch.ElapsedMilliseconds / (500d * repeat);

File.Create($"{instanceSize};{instanceAverage}.txt");

bfWatch.Reset();
GC.Collect();
}
}

static void MeasureRelativeErrors(string directoryPath)
{
if (!Directory.Exists(directoryPath))
{
Console.WriteLine("Directory '{0}' does not exist.", directoryPath);
return;
}

var knapsacksFiles = Directory.EnumerateFiles(directoryPath, "knap_*.dat").ToList();
var relativeErrors = new List<double>();

for (int i = 0; i < knapsacksFiles.Count; i += 2)
{
var file = knapsacksFiles[i];
var solutionFile = knapsacksFiles[i + 1];
var bestPrices = File.ReadAllLines(solutionFile).Select(line => double.Parse(line.Split()[2])).ToList();

var knapsacks = KnapsackLoader.LoadKnapsacks(file, 500).ToList();
for (int j = 0; j < knapsacks.Count; j++)
{
var result = KnapsackProblemSolver.PriceToWeightRatioHeuristics(knapsacks[j]);
relativeErrors.Add((bestPrices[j] - result.Item1) / bestPrices[j]);
}
}

Console.WriteLine($"Average relative error from {relativeErrors.Count} different errors is {relativeErrors.Average()}.");
Console.WriteLine("Max relative error is {0}.", relativeErrors.Max());
}
}
}
15 changes: 0 additions & 15 deletions KnapsackProblem.BruteForce/Program.cs

This file was deleted.

30 changes: 30 additions & 0 deletions KnapsackProblem.Common/Helpers.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using System.Text;

namespace KnapsackProblem.Common
{
public static class Helpers
{
/// <summary>
/// Returns a specific binary format of a ulong value.
/// </summary>
public static string ToReverseBinary(this ulong value, int binaryDigitsCount)
{
var sb = new StringBuilder();
int binaryDigits = 0;
while (value != 0)
{
sb.Append((value & 1) == 1 ? " 1" : " 0");
value >>= 1;
binaryDigits++;
}

while (binaryDigits < binaryDigitsCount)
{
sb.Append(" 0");
binaryDigits++;
}

return sb.ToString();
}
}
}
23 changes: 23 additions & 0 deletions KnapsackProblem.Common/Knapsack.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System.Collections.Generic;
using System.Linq;

namespace KnapsackProblem.Common
{
public sealed class Knapsack
{
public short Id { get; }
public short Capacity { get; }
public int InstanceSize => Items.Count;

public List<KnapsackItem> Items { get; }

public Knapsack(short id, short capacity, IEnumerable<KnapsackItem> items)
{
Id = id;
Capacity = capacity;
Items = items.ToList();
}

public override string ToString() => $"knapsack {Id}, capacity: {Capacity}";
}
}
16 changes: 16 additions & 0 deletions KnapsackProblem.Common/KnapsackItem.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
namespace KnapsackProblem.Common
{
public struct KnapsackItem
{
public ushort Weight { get; }
public ushort Price { get; }

public KnapsackItem(ushort weight, ushort price)
{
Weight = weight;
Price = price;
}

public override string ToString() => $"weight: {Weight}, price: {Price}";
}
}
Loading

0 comments on commit cb643a2

Please sign in to comment.