Moved nesting to SawCut library

This commit is contained in:
AJ
2021-10-04 19:06:33 -04:00
parent 793c6173b1
commit 44f3cbfa81
18 changed files with 186 additions and 86 deletions

76
SawCut/ArchUnits.cs Normal file
View File

@@ -0,0 +1,76 @@
using System;
using System.Text.RegularExpressions;
using System.Text;
using SawCut;
namespace SawCut
{
public static class ArchUnits
{
public static double ParseToInches(string input)
{
if (string.IsNullOrWhiteSpace(input))
return 0;
var sb = new StringBuilder(input.Trim().ToLower());
// replace all units with their equivelant symbols
sb.Replace("ft", "'");
sb.Replace("feet", "'");
sb.Replace("foot", "'");
sb.Replace("inches", "\"");
sb.Replace("inch", "\"");
sb.Replace("in", "\"");
var regex = new Regex("^(?<Feet>\\d+\\.?\\d*\\s*')?\\s*(?<Inches>\\d+\\.?\\d*\\s*\")?$");
// input manipulation is done, put the value back
input = Fraction.ReplaceFractionsWithDecimals(sb.ToString());
var match2 = regex.Match(input);
if (!match2.Success)
throw new Exception("Input is not in a valid format.");
var feet = match2.Groups["Feet"];
var inches = match2.Groups["Inches"];
var totalInches = 0.0;
if (feet.Success)
{
var x = double.Parse(feet.Value.Remove(feet.Length - 1));
totalInches += x * 12;
}
if (inches.Success)
{
var x = double.Parse(inches.Value.Remove(inches.Length - 1));
totalInches += x;
}
return Math.Round(totalInches, 8);
}
public static double ParseToFeet(string input)
{
var inches = ParseToInches(input);
return Math.Round(inches / 12.0, 8);
}
public static string FormatFromInches(double totalInches)
{
var feet = Math.Floor(totalInches / 12.0);
var inches = totalInches - (feet * 12.0);
if (feet > 0)
{
return $"{feet}' {inches}\"";
}
else
{
return $"{inches}\"";
}
}
}
}

48
SawCut/Bin.cs Normal file
View File

@@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace SawCut
{
public class Bin
{
public List<BinItem> Items;
public Bin(double length)
{
Items = new List<BinItem>();
Length = length;
}
public double Spacing { get; set; }
public double Length { get; set; }
public double UsedLength
{
get
{
return Math.Round(Items.Sum(i => i.Length) + Spacing * Items.Count, 8);
}
}
public double RemainingLength
{
get { return Math.Round(Length - UsedLength, 8); }
}
public double Utilization
{
get { return UsedLength / Length; }
}
public override string ToString()
{
var totalLength = Math.Round(Length, 4);
var remainingLength = Math.Round(RemainingLength, 4);
var utilitation = Math.Round(Utilization * 100, 2);
return $"Length: {totalLength}\", {remainingLength}\" remaining, {Items.Count} items, {utilitation}% utilization";
}
}
}

9
SawCut/BinItem.cs Normal file
View File

@@ -0,0 +1,9 @@
namespace SawCut
{
public class BinItem
{
public string Name { get; set; }
public double Length { get; set; }
}
}

85
SawCut/Fraction.cs Normal file
View File

@@ -0,0 +1,85 @@
using System;
using System.Text.RegularExpressions;
using System.Text;
using System.Linq;
namespace SawCut
{
public static class Fraction
{
public static readonly Regex FractionRegex = new Regex(@"((?<WholeNum>\d+)(\ |-))?(?<Fraction>\d+\/\d+)");
public static bool IsValid(string s)
{
return FractionRegex.IsMatch(s);
}
public static double Parse(string s)
{
var match = FractionRegex.Match(s);
if (!match.Success)
throw new Exception("Invalid format.");
var value = 0.0;
var wholeNumGroup = match.Groups["WholeNum"];
var fractionGroup = match.Groups["Fraction"];
if (wholeNumGroup.Success)
{
value = double.Parse(wholeNumGroup.Value);
}
if (fractionGroup.Success)
{
var parts = fractionGroup.Value.Split('/');
var numerator = double.Parse(parts[0]);
var denominator = double.Parse(parts[1]);
value += Math.Round(numerator / denominator, 8);
}
return value;
}
public static string ReplaceFractionsWithDecimals(string input)
{
var sb = new StringBuilder(input);
// find all matches and sort by descending index number to avoid
// changing all previous index numbers when the fraction is replaced
// with the decimal equivalent.
var fractionMatches = FractionRegex.Matches(sb.ToString())
.Cast<Match>()
.OrderByDescending(m => m.Index);
foreach (var fractionMatch in fractionMatches)
{
// convert the fraction to a decimal value
var decimalValue = Parse(fractionMatch.Value);
// remove the fraction and insert the decimal value in its place.
sb.Remove(fractionMatch.Index, fractionMatch.Length);
sb.Insert(fractionMatch.Index, decimalValue);
}
return sb.ToString();
}
public static bool TryParse(string s, out double fraction)
{
try
{
fraction = Parse(s);
}
catch
{
fraction = 0;
return false;
}
return true;
}
}
}

View File

@@ -0,0 +1,91 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
namespace SawCut.Nesting
{
public class BestFitEngine : IEngine
{
public double StockLength { get; set; }
public double Spacing { get; set; }
private List<BinItem> Items { get; set; }
public Result Pack(List<BinItem> items)
{
if (StockLength <= 0)
throw new Exception("Stock length must be greater than 0");
Items = items.OrderByDescending(i => i.Length).ToList();
var result = new Result();
result.ItemsNotUsed = Items.Where(i => i.Length > StockLength).ToList();
foreach (var item in result.ItemsNotUsed)
{
Items.Remove(item);
}
result.Bins = GetBins();
return result;
}
private List<Bin> GetBins()
{
var bins = new List<Bin>();
foreach (var item in Items)
{
Bin best_bin;
if (!FindBin(bins.ToArray(), item.Length, out best_bin))
{
if (item.Length > StockLength)
continue;
best_bin = CreateBin();
bins.Add(best_bin);
}
best_bin.Items.Add(item);
}
return bins
.OrderByDescending(b => b.Utilization)
.ThenBy(b => b.Items.Count)
.ToList();
}
private Bin CreateBin()
{
var length = StockLength;
return new Bin(length)
{
Spacing = Spacing
};
}
private static bool FindBin(IEnumerable<Bin> bins, double length, out Bin found)
{
found = null;
foreach (var bin in bins)
{
if (bin.RemainingLength < length)
continue;
if (found == null)
found = bin;
if (bin.RemainingLength < found.RemainingLength)
found = bin;
}
return (found != null);
}
}
}

146
SawCut/Nesting/Engine2.cs Normal file
View File

@@ -0,0 +1,146 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
namespace SawCut.Nesting
{
public class Engine2 : IEngine
{
public double StockLength { get; set; }
public double Spacing { get; set; }
private List<BinItem> Items { get; set; }
public Result Pack(List<BinItem> items)
{
if (StockLength <= 0)
throw new Exception("Stock length must be greater than 0");
Items = items.OrderByDescending(i => i.Length).ToList();
var result = new Result();
result.ItemsNotUsed = Items.Where(i => i.Length > StockLength).ToList();
foreach (var item in result.ItemsNotUsed)
{
Items.Remove(item);
}
result.Bins = GetBins();
return result;
}
private List<Bin> GetBins()
{
var bins = new List<Bin>();
while (Items.Count > 0)
{
var bin = new Bin(StockLength);
bin.Spacing = Spacing;
FillBin(bin);
int count = 0;
while (TryImprovePacking(bin))
{
count++;
}
bins.Add(bin);
}
return bins
.OrderByDescending(b => b.Utilization)
.ThenBy(b => b.Items.Count)
.ToList();
}
private void FillBin(Bin bin)
{
for (int i = 0; i < Items.Count; i++)
{
var item = Items[i];
if (bin.RemainingLength >= item.Length)
bin.Items.Add(item);
}
foreach (var item in bin.Items)
{
Items.Remove(item);
}
}
private bool TryImprovePacking(Bin bin)
{
if (bin.Items.Count == 0)
return false;
if (Items.Count < 2)
return false;
var lengthGroups = bin.Items
.OrderByDescending(i => i.Length)
.GroupBy(i => i.Length)
.Skip(1);
var minItemLength = Items.Min(i => i.Length);
foreach (var group in lengthGroups)
{
var minRemainingLength = bin.RemainingLength;
var firstItem = group.First();
bin.Items.Remove(firstItem);
for (int i = 0; i < Items.Count; i++)
{
var item1 = Items[i];
if (Items[i].Length > bin.RemainingLength)
continue;
var bin2 = new Bin(bin.RemainingLength);
bin2.Spacing = bin.Spacing;
bin2.Items.Add(item1);
for (int j = i + 1; j < Items.Count; j++)
{
if (bin2.RemainingLength < minItemLength)
break;
var item2 = Items[j];
if (item2.Length > bin2.RemainingLength)
continue;
bin2.Items.Add(item2);
}
if (bin2.RemainingLength < minRemainingLength)
{
Items.Add(firstItem);
bin.Items.AddRange(bin2.Items);
foreach (var item in bin2.Items)
{
Items.Remove(item);
}
// improvement made
return true;
}
}
bin.Items.Add(firstItem);
}
return false;
}
}
}

View File

@@ -0,0 +1,9 @@
using System.Collections.Generic;
namespace SawCut.Nesting
{
public interface IEngine
{
Result Pack(List<BinItem> items);
}
}

16
SawCut/Nesting/Result.cs Normal file
View File

@@ -0,0 +1,16 @@
using System.Collections.Generic;
namespace SawCut.Nesting
{
public class Result
{
public Result()
{
ItemsNotUsed = new List<BinItem>();
}
public List<BinItem> ItemsNotUsed { get; set; }
public List<Bin> Bins { get; set; }
}
}

View File

@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SawCut")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SawCut")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3d873ff0-6930-4bce-a5a9-da5c20354dee")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

55
SawCut/SawCut.csproj Normal file
View File

@@ -0,0 +1,55 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" 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>{3D873FF0-6930-4BCE-A5A9-DA5C20354DEE}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SawCut</RootNamespace>
<AssemblyName>SawCut</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<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' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="ArchUnits.cs" />
<Compile Include="Bin.cs" />
<Compile Include="BinItem.cs" />
<Compile Include="Fraction.cs" />
<Compile Include="Nesting\BestFitEngine.cs" />
<Compile Include="Nesting\IEngine.cs" />
<Compile Include="Nesting\Result.cs" />
<Compile Include="Nesting\Engine2.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>