├── LICENSE ├── data.csv ├── solved ├── data.csv ├── data.fsx ├── level-1-feasibility.fsx ├── level-2-allocation.fsx ├── level-4-traveling-salesman.fsx └── level-3-distribution.fsx ├── data.fsx ├── README.md ├── level-1-feasibility.fsx ├── level-2-allocation.fsx ├── level-3-distribution.fsx ├── level-4-traveling-salesman.fsx └── .gitignore /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Mathias Brandewinder 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /data.csv: -------------------------------------------------------------------------------- 1 | Austria (10) Vienna 47.51669707 9.766701588 2 | Belgium (10) Brussels 50.44599911 3.939003561 3 | Bulgaria (18) Sofia 43.13799911 24.71900459 4 | Croatia (10) Zagreb 43.7272222 15.9058333 5 | Cyprus (4) Nicosia 34.9170031 33.63599757 6 | Czech Republic (12) Prague 50.66299816 14.08100455 7 | Denmark (12) Copenhagen 55.70900103 9.534996498 8 | Estonia (7) Tallinn 58.9430556 23.5413889 9 | Finland (21) Helsinki 60.99699611 24.47199954 10 | France (71) Paris 45.89997479 6.116670287 11 | Germany (57) Berlin 49.98247246 8.273219156 12 | Greece (30) Athens 38.89899915 22.43400358 13 | Hungary (20) Budapest 47.09099714 17.91099957 14 | Ireland (15) Dublin 53.6333333 -8.1833333 15 | Italy (56) Rome 40.64200213 15.7989965 16 | Latvia (6) Riga 56.50002545 27.3165649 17 | Lithuania (5) Vilnius 55.74002016 24.37002641 18 | Luxembourg (3) Luxembourg 49.88330105 6.166701555 19 | Malta (1) Valletta 35.89973248 14.51471065 20 | Netherlands (14) Amsterdam 53.00000109 6.550002585 21 | Poland (24) Warsaw 53.80003522 20.48003129 22 | Portugal (24) Lisbon 40.64100311 -8.650997534 23 | Romania (41) Bucharest 45.04500004 23.27400062 24 | Slovakia (7) Bratislava 48.73329022 19.14998328 25 | Slovenia (2) Ljubljana 46.54047833 15.65004187 26 | Spain (49) Madrid 38.91200402 -6.337997512 27 | Sweden (34) Stockholm 60.61300204 15.64700455 -------------------------------------------------------------------------------- /solved/data.csv: -------------------------------------------------------------------------------- 1 | Austria (10) Vienna 47.51669707 9.766701588 2 | Belgium (10) Brussels 50.44599911 3.939003561 3 | Bulgaria (18) Sofia 43.13799911 24.71900459 4 | Croatia (10) Zagreb 43.7272222 15.9058333 5 | Cyprus (4) Nicosia 34.9170031 33.63599757 6 | Czech Republic (12) Prague 50.66299816 14.08100455 7 | Denmark (12) Copenhagen 55.70900103 9.534996498 8 | Estonia (7) Tallinn 58.9430556 23.5413889 9 | Finland (21) Helsinki 60.99699611 24.47199954 10 | France (71) Paris 45.89997479 6.116670287 11 | Germany (57) Berlin 49.98247246 8.273219156 12 | Greece (30) Athens 38.89899915 22.43400358 13 | Hungary (20) Budapest 47.09099714 17.91099957 14 | Ireland (15) Dublin 53.6333333 -8.1833333 15 | Italy (56) Rome 40.64200213 15.7989965 16 | Latvia (6) Riga 56.50002545 27.3165649 17 | Lithuania (5) Vilnius 55.74002016 24.37002641 18 | Luxembourg (3) Luxembourg 49.88330105 6.166701555 19 | Malta (1) Valletta 35.89973248 14.51471065 20 | Netherlands (14) Amsterdam 53.00000109 6.550002585 21 | Poland (24) Warsaw 53.80003522 20.48003129 22 | Portugal (24) Lisbon 40.64100311 -8.650997534 23 | Romania (41) Bucharest 45.04500004 23.27400062 24 | Slovakia (7) Bratislava 48.73329022 19.14998328 25 | Slovenia (2) Ljubljana 46.54047833 15.65004187 26 | Spain (49) Madrid 38.91200402 -6.337997512 27 | Sweden (34) Stockholm 60.61300204 15.64700455 -------------------------------------------------------------------------------- /data.fsx: -------------------------------------------------------------------------------- 1 | // https://www.distancelatlong.com/all/countries/ 2 | 3 | open System 4 | open System.IO 5 | 6 | type Coordinates = { 7 | Lat: float 8 | Lon: float 9 | } 10 | 11 | type Country = { 12 | Name: string 13 | Population: float 14 | Capital: string 15 | Coords: Coordinates 16 | } 17 | 18 | let countries = 19 | "data.csv" 20 | |> File.ReadAllLines 21 | |> Array.map (fun line -> 22 | printfn $"{line}" 23 | let block = line.Split '\t' 24 | let x = block.[0].IndexOf("(") 25 | let y = block.[0].IndexOf(")") 26 | let name = block.[0].[0 .. x - 1].Trim() 27 | let population = block.[0].[x + 1 .. y - 1] |> float 28 | { 29 | Name = name 30 | Population = population 31 | Capital = block.[1] 32 | Coords = { 33 | Lat = block.[2] |> float 34 | Lon = block.[3] |> float 35 | } 36 | } 37 | ) 38 | 39 | let distance (coords1: Coordinates) (coords2: Coordinates) = 40 | 41 | let lat1 = coords1.Lat 42 | let lon1 = coords1.Lon 43 | 44 | let lat2 = coords2.Lat 45 | let lon2 = coords2.Lon 46 | 47 | let r = 6371.0 48 | let p = Math.PI / 180.0 49 | 50 | let a = 51 | 0.5 52 | - 53 | cos((lat2 - lat1) * p) / 2.0 54 | + 55 | cos(lat1 * p) * cos(lat2 * p) * (1.0 - cos((lon2 - lon1) * p)) / 2.0 56 | 57 | 2.0 * r * asin(sqrt(a)) 58 | 59 | let c1 = countries.[0] 60 | let c2 = countries.[1] 61 | let f = countries |> Array.find (fun x -> x.Name = "France") 62 | let g = countries |> Array.find (fun x -> x.Name = "Germany") 63 | 64 | distance (c1.Coords) (c2.Coords) 65 | distance (c1.Coords) (f.Coords) 66 | distance (f.Coords) (g.Coords) 67 | 68 | countries 69 | |> Array.map (fun x -> 70 | x.Capital, distance g.Coords x.Coords 71 | ) 72 | 73 | // long ~ 3000 kms 74 | countries 75 | |> Array.collect (fun origin -> 76 | countries 77 | |> Array.map (fun dest -> 78 | (origin.Name, dest.Name), 79 | distance origin.Coords dest.Coords 80 | ) 81 | ) 82 | |> Array.sortByDescending (fun (_, d) -> d) 83 | |> Array.take 50 84 | -------------------------------------------------------------------------------- /solved/data.fsx: -------------------------------------------------------------------------------- 1 | // https://www.distancelatlong.com/all/countries/ 2 | 3 | open System 4 | open System.IO 5 | 6 | type Coordinates = { 7 | Lat: float 8 | Lon: float 9 | } 10 | 11 | type Country = { 12 | Name: string 13 | Population: float 14 | Capital: string 15 | Coords: Coordinates 16 | } 17 | 18 | let countries = 19 | "data.csv" 20 | |> File.ReadAllLines 21 | |> Array.map (fun line -> 22 | printfn $"{line}" 23 | let block = line.Split '\t' 24 | let x = block.[0].IndexOf("(") 25 | let y = block.[0].IndexOf(")") 26 | let name = block.[0].[0 .. x - 1].Trim() 27 | let population = block.[0].[x + 1 .. y - 1] |> float 28 | { 29 | Name = name 30 | Population = population 31 | Capital = block.[1] 32 | Coords = { 33 | Lat = block.[2] |> float 34 | Lon = block.[3] |> float 35 | } 36 | } 37 | ) 38 | 39 | let distance (coords1: Coordinates) (coords2: Coordinates) = 40 | 41 | let lat1 = coords1.Lat 42 | let lon1 = coords1.Lon 43 | 44 | let lat2 = coords2.Lat 45 | let lon2 = coords2.Lon 46 | 47 | let r = 6371.0 48 | let p = Math.PI / 180.0 49 | 50 | let a = 51 | 0.5 52 | - 53 | cos((lat2 - lat1) * p) / 2.0 54 | + 55 | cos(lat1 * p) * cos(lat2 * p) * (1.0 - cos((lon2 - lon1) * p)) / 2.0 56 | 57 | 2.0 * r * asin(sqrt(a)) 58 | 59 | let c1 = countries.[0] 60 | let c2 = countries.[1] 61 | let f = countries |> Array.find (fun x -> x.Name = "France") 62 | let g = countries |> Array.find (fun x -> x.Name = "Germany") 63 | 64 | distance (c1.Coords) (c2.Coords) 65 | distance (c1.Coords) (f.Coords) 66 | distance (f.Coords) (g.Coords) 67 | 68 | countries 69 | |> Array.map (fun x -> 70 | x.Capital, distance g.Coords x.Coords 71 | ) 72 | 73 | // long ~ 3000 kms 74 | countries 75 | |> Array.collect (fun origin -> 76 | countries 77 | |> Array.map (fun dest -> 78 | (origin.Name, dest.Name), 79 | distance origin.Coords dest.Coords 80 | ) 81 | ) 82 | |> Array.sortByDescending (fun (_, d) -> d) 83 | |> Array.take 50 84 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 4-levels-of-linear-programming 2 | 3 | ## Introduction 4 | 5 | You have been contacted by the FSharp Corporation, a thriving business that 6 | ships FSharp all over countries of the European Union. 7 | 8 | Each country needs a steady monthly supply of FSharp. A smaller country like 9 | Austria needs to receive 10 units of F# each month, whereas a larger country 10 | like Germany needs 57 units of F# each month. 11 | 12 | The FSharp Corporation operates 5 factories, spread out in the European Union. 13 | Each factory can produce a limited quantity of F# units every month, and is 14 | assigned a list of countries it can ship to. 15 | 16 | However, due to an increase in F# demand, Management has noticed that there 17 | were issues with producing and shipping units where they are needed. Your task 18 | is to analyze the setup, and optimize it! 19 | 20 | - data.csv file 21 | - data.fsx file 22 | 23 | ## Level 1: Feasibility 24 | 25 | We have 5 factories. 26 | Each factory has 27 | - a capacity (150 units), and 28 | - a list of countries it can ship to. 29 | 30 | The total demand across countries is 563 units, we can produce 5 * 150 units. 31 | Can we actually meet the demand? 32 | 33 | ## Level 2: Linear Programming / Allocation 34 | 35 | We start from the same setup as Level 1, but we want to figure out what is the 36 | most profitable way we can ship units with our current factories. 37 | 38 | Changes from Level 1: 39 | 40 | - Every factory now has a Location, the country where it is located. 41 | - When we ship and sell a unit from a factory to a destination country, we 42 | receive $1.0, but we incur costs based on the shipping distance. 43 | 44 | As a result, the solver should try to favor shipping from closer factories, 45 | because its objective is to maximize profit. 46 | 47 | ## Level 3: Mixed Integer Linear Programming 48 | 49 | We start from a setup similar to Level 2, but we want to change our factories 50 | to become more profitable. We allow two changes: 51 | 52 | - we can now ship from any factory to any country, 53 | - we can change the size of each factory. We assign 0 to 10 machines to each 54 | factory, with each machine costing 10 but bringing a capacity of 50 units. 55 | 56 | ## Level 4: Mixed Integer Linear Programming / Traveling Salesman 57 | 58 | This problem is mostly independent from Level 1 to 3. 59 | 60 | We take on the classic Traveling Salesman Problem, and try to find the shortest 61 | route that visits all our cities, once, and returns to the origin. 62 | 63 | ## References 64 | 65 | Google OR Tools: 66 | https://developers.google.com/optimization 67 | 68 | FLIPS: 69 | https://flipslibrary.com 70 | 71 | Formulating Integer Linear Programs: A Rogues’ Gallery 72 | https://faculty.nps.edu/dell/docs/Formulettes060425.pdf 73 | 74 | https://cs.stackexchange.com/questions/12102/express-boolean-logic-operations-in-zero-one-integer-linear-programming-ilp 75 | 76 | https://math.stackexchange.com/questions/2500415/how-to-write-if-else-statement-in-linear-programming -------------------------------------------------------------------------------- /level-1-feasibility.fsx: -------------------------------------------------------------------------------- 1 | #load "data.fsx" 2 | open Data 3 | 4 | // 563.0 5 | countries 6 | |> Array.sumBy (fun x -> x.Population) 7 | 8 | let factory1 = countries.[ 0 .. 9 ] |> Array.map (fun x -> x.Name) 9 | let factory2 = countries.[ 0 .. 4 ] |> Array.map (fun x -> x.Name) 10 | let factory3 = countries.[ 10 .. ] |> Array.map (fun x -> x.Name) 11 | let factory4 = countries.[ 10 .. 14 ] |> Array.map (fun x -> x.Name) 12 | let factory5 = countries.[ 13 .. 14 ] |> Array.map (fun x -> x.Name) 13 | 14 | // Each factory has a list of countries it can ship to 15 | let factories = 16 | [ 17 | "FACTORY 1", factory1 18 | "FACTORY 2", factory2 19 | "FACTORY 3", factory3 20 | "FACTORY 4", factory4 21 | "FACTORY 5", factory5 22 | ] 23 | |> Map.ofList 24 | 25 | let capacity = 150.0 26 | // total capacity: 150 * 5 = 750 > demand = 563 27 | 28 | 29 | #r "nuget: Google.OrTools, Version=9.7.2996" 30 | open Google.OrTools.LinearSolver 31 | 32 | // Pure Linear Programming solver 33 | let solver = Solver.CreateSolver("GLOP") 34 | 35 | // variables: shipments (origin, destination) 36 | // ----------------------------------------------------------------------------- 37 | 38 | type Shipment = { 39 | Origin: string 40 | Destination: string 41 | } 42 | 43 | 44 | let variables = 45 | [| 46 | for KeyValue(factory,destinations) in factories do 47 | for country in destinations do 48 | let shipment = { Origin = factory; Destination = country } 49 | let variable = solver.MakeNumVar(0.0, capacity, $"{factory}-{country}") 50 | shipment, variable 51 | |] 52 | |> Map.ofSeq 53 | 54 | // production capacity constraint 55 | // constraint: each factory can ship only up to its capacity 56 | // ----------------------------------------------------------------------------- 57 | 58 | factories 59 | |> Map.iter (fun factory destinations -> 60 | let c = solver.MakeConstraint(0.0, capacity, $"Capacity {factory}") 61 | variables 62 | |> Map.filter (fun shipment variable -> 63 | shipment.Origin = factory 64 | ) 65 | |> Map.iter (fun shipment variable -> 66 | c.SetCoefficient(variable, 1.0) 67 | ) 68 | ) 69 | 70 | // demand constraint 71 | // constraint: each country must receive its demand 72 | // ----------------------------------------------------------------------------- 73 | 74 | countries 75 | |> Array.iter (fun country -> 76 | let c = 77 | solver.MakeConstraint( 78 | country.Population, 79 | country.Population, 80 | $"Demand {country}" 81 | ) 82 | 83 | // TODO 84 | // Setup the coefficients of the relevant variables 85 | failwith "TODO" 86 | ) 87 | 88 | // ... and solve 89 | // Note: we do not even specify an objective function. 90 | // All we care about is "is there even 1 set of variables that works" 91 | // ----------------------------------------------------------------------------- 92 | 93 | let solution = solver.Solve() 94 | 95 | // ----------------------------------------------------------------------------- 96 | // What is the result? 97 | // At what capacity does the problem become infeasible / feasible? -------------------------------------------------------------------------------- /solved/level-1-feasibility.fsx: -------------------------------------------------------------------------------- 1 | #load "data.fsx" 2 | open Data 3 | 4 | // 563.0 5 | countries 6 | |> Array.sumBy (fun x -> x.Population) 7 | 8 | let factory1 = countries.[ 0 .. 9 ] |> Array.map (fun x -> x.Name) 9 | let factory2 = countries.[ 0 .. 4 ] |> Array.map (fun x -> x.Name) 10 | let factory3 = countries.[ 10 .. ] |> Array.map (fun x -> x.Name) 11 | let factory4 = countries.[ 10 .. 14 ] |> Array.map (fun x -> x.Name) 12 | let factory5 = countries.[ 13 .. 14 ] |> Array.map (fun x -> x.Name) 13 | 14 | // Each factory has a list of countries it can ship to 15 | let factories = 16 | [ 17 | "FACTORY 1", factory1 18 | "FACTORY 2", factory2 19 | "FACTORY 3", factory3 20 | "FACTORY 4", factory4 21 | "FACTORY 5", factory5 22 | ] 23 | |> Map.ofList 24 | 25 | let capacity = 150.0 26 | // total capacity: 150 * 5 = 750 > demand = 563 27 | 28 | 29 | #r "nuget: Google.OrTools, Version=9.7.2996" 30 | open Google.OrTools.LinearSolver 31 | 32 | // Pure Linear Programming solver 33 | let solver = Solver.CreateSolver("GLOP") 34 | 35 | // variables: shipments (origin, destination) 36 | // ----------------------------------------------------------------------------- 37 | 38 | type Shipment = { 39 | Origin: string 40 | Destination: string 41 | } 42 | 43 | let variables = 44 | [| 45 | for KeyValue(factory,destinations) in factories do 46 | for country in destinations do 47 | let shipment = { Origin = factory; Destination = country } 48 | let variable = solver.MakeNumVar(0.0, capacity, $"{factory}-{country}") 49 | shipment, variable 50 | |] 51 | |> Map.ofSeq 52 | 53 | // production capacity constraint 54 | // constraint: each factory can ship only up to its capacity 55 | // ----------------------------------------------------------------------------- 56 | 57 | factories 58 | |> Map.iter (fun factory destinations -> 59 | let c = solver.MakeConstraint(0.0, capacity, $"Capacity {factory}") 60 | variables 61 | |> Map.filter (fun shipment variable -> 62 | shipment.Origin = factory 63 | ) 64 | |> Map.iter (fun shipment variable -> 65 | c.SetCoefficient(variable, 1.0) 66 | ) 67 | ) 68 | 69 | // demand constraint 70 | // constraint: each country must receive its demand 71 | // ----------------------------------------------------------------------------- 72 | 73 | countries 74 | |> Array.iter (fun country -> 75 | let c = 76 | solver.MakeConstraint( 77 | country.Population, 78 | country.Population, 79 | $"Demand {country}" 80 | ) 81 | variables 82 | |> Map.filter (fun shipment variable -> 83 | shipment.Destination = country.Name 84 | ) 85 | |> Map.iter (fun shipment variable -> 86 | c.SetCoefficient(variable, 1.0) 87 | ) 88 | ) 89 | 90 | // ... and solve 91 | // Note: we do not even specify an objective function. 92 | // All we care about is "is there even 1 set of variables that works" 93 | // ----------------------------------------------------------------------------- 94 | 95 | let solution = solver.Solve() 96 | 97 | // ----------------------------------------------------------------------------- 98 | // What is the result? 99 | // At what capacity does it become infeasible / feasible? -------------------------------------------------------------------------------- /level-2-allocation.fsx: -------------------------------------------------------------------------------- 1 | #load "data.fsx" 2 | open Data 3 | 4 | // 563.0 5 | countries 6 | |> Array.sumBy (fun x -> x.Population) 7 | 8 | // units per factory per unit of time 9 | let capacity = 150.0 10 | 11 | // NEW: MODIFIED FROM PREVIOUS SCRIPT 12 | let unitSalePrice = 1.0 // price per unit sold 13 | // large distance ~ 3000 kms 14 | let transportationCost = 1.0 / 2500. 15 | 16 | // countries served 17 | let factory1 = countries.[ 0 .. 9 ] |> Array.map (fun x -> x.Name) 18 | let factory2 = countries.[ 0 .. 4 ] |> Array.map (fun x -> x.Name) 19 | let factory3 = countries.[ 10 .. ] |> Array.map (fun x -> x.Name) 20 | let factory4 = countries.[ 10 .. 14 ] |> Array.map (fun x -> x.Name) 21 | let factory5 = countries.[ 13 .. 14 ] |> Array.map (fun x -> x.Name) 22 | 23 | let factories = 24 | [ 25 | "FACTORY 1", factory1 26 | "FACTORY 2", factory2 27 | "FACTORY 3", factory3 28 | "FACTORY 4", factory4 29 | "FACTORY 5", factory5 30 | ] 31 | |> Map.ofList 32 | 33 | // NEW: MODIFIED FROM PREVIOUS SCRIPT 34 | // Each factory is located in a country 35 | let factoryLocations = 36 | [ 37 | "FACTORY 1", countries.[0] 38 | "FACTORY 2", countries.[4] 39 | "FACTORY 3", countries.[10] 40 | "FACTORY 4", countries.[14] 41 | "FACTORY 5", countries.[13] 42 | ] 43 | |> Map.ofList 44 | 45 | #r "nuget: Google.OrTools, Version=9.7.2996" 46 | open Google.OrTools.LinearSolver 47 | 48 | // Pure Linear Programming solver 49 | let solver = Solver.CreateSolver("GLOP") 50 | 51 | // variables: shipments (origin, destination) 52 | // ----------------------------------------------------------------------------- 53 | 54 | type Shipment = { 55 | Origin: string 56 | Destination: string 57 | } 58 | 59 | let variables = 60 | factories 61 | |> Seq.collect (fun kv -> 62 | let factory = kv.Key 63 | let destinations = kv.Value 64 | destinations 65 | |> Seq.map (fun country -> 66 | { Origin = factory; Destination = country }, 67 | solver.MakeNumVar(0.0, capacity, $"{factory}-{country}") 68 | ) 69 | ) 70 | |> Map.ofSeq 71 | 72 | // production capacity constraint 73 | // constraint: each factory can ship only up to its capacity 74 | // ----------------------------------------------------------------------------- 75 | 76 | factories 77 | |> Map.iter (fun factory destinations -> 78 | let c = solver.MakeConstraint(0.0, capacity, $"Capacity {factory}") 79 | variables 80 | |> Map.filter (fun shipment variable -> 81 | shipment.Origin = factory 82 | ) 83 | |> Map.iter (fun shipment variable -> 84 | c.SetCoefficient(variable, 1.0) 85 | ) 86 | ) 87 | 88 | // demand constraint 89 | // constraint: each country can receive up to its demand 90 | // ----------------------------------------------------------------------------- 91 | 92 | countries 93 | |> Array.iter (fun country -> 94 | let c = 95 | solver.MakeConstraint( 96 | // NEW: MODIFIED FROM PREVIOUS SCRIPT 97 | 0.0, 98 | country.Population, 99 | $"Demand {country}" 100 | ) 101 | variables 102 | |> Map.filter (fun shipment variable -> 103 | shipment.Destination = country.Name 104 | ) 105 | |> Map.iter (fun shipment variable -> 106 | c.SetCoefficient(variable, 1.0) 107 | ) 108 | ) 109 | 110 | // Objective 111 | // We want to maximize profit 112 | // ----------------------------------------------------------------------------- 113 | 114 | let objective = solver.Objective() 115 | objective.SetMaximization() 116 | 117 | variables 118 | |> Map.iter (fun shipment variable -> 119 | // country where the shipment comes from 120 | let origin = 121 | countries 122 | |> Array.find (fun x -> 123 | x.Name = factoryLocations.[shipment.Origin].Name 124 | ) 125 | // country where the shipment goes to 126 | let dest = 127 | countries 128 | |> Array.find (fun x -> 129 | x.Name = shipment.Destination 130 | ) 131 | 132 | // TODO 133 | // Setup the coefficients of the relevant variables, 134 | // so that each unit produces a profit of 135 | // unitSalePrice - travelDistance * transportationCost 136 | failwith "TODO" 137 | ) 138 | 139 | // ... and solve 140 | let solution = solver.Solve() 141 | 142 | // We can observe how big each shipment should be 143 | variables 144 | |> Map.iter (fun k v -> printfn $"{k}: {v.SolutionValue()}") 145 | 146 | // Which factories are fully utilized? Which are barely utilized? 147 | // Are we shipping all we could ship? 148 | // Which countries get / don't get all they wanted? Why? 149 | -------------------------------------------------------------------------------- /level-3-distribution.fsx: -------------------------------------------------------------------------------- 1 | #load "data.fsx" 2 | open Data 3 | 4 | // 563.0 5 | countries 6 | |> Array.sumBy (fun x -> x.Population) 7 | 8 | // fixed capacity is gone 9 | // let capacity = 200.0 10 | 11 | // NEW: MODIFIED FROM PREVIOUS SCRIPT 12 | let machineCapacity = 50.0 13 | // NEW: MODIFIED FROM PREVIOUS SCRIPT 14 | let machineCost = 10.0 15 | let unitSalePrice = 1.0 // price per unit sold 16 | // large distance ~ 3000 kms 17 | let transportationCost = 1.0 / 2500. 18 | 19 | // countries served 20 | let factory1 = countries |> Array.map (fun x -> x.Name) 21 | let factory2 = countries |> Array.map (fun x -> x.Name) 22 | let factory3 = countries |> Array.map (fun x -> x.Name) 23 | let factory4 = countries |> Array.map (fun x -> x.Name) 24 | let factory5 = countries |> Array.map (fun x -> x.Name) 25 | 26 | let factories = 27 | [ 28 | "FACTORY 1", factory1 29 | "FACTORY 2", factory2 30 | "FACTORY 3", factory3 31 | "FACTORY 4", factory4 32 | "FACTORY 5", factory5 33 | ] 34 | |> Map.ofList 35 | 36 | let factoryLocations = 37 | [ 38 | "FACTORY 1", countries.[0] 39 | "FACTORY 2", countries.[4] 40 | "FACTORY 3", countries.[10] 41 | "FACTORY 4", countries.[14] 42 | "FACTORY 5", countries.[13] 43 | ] 44 | |> Map.ofList 45 | 46 | (* 47 | Austria 48 | Cyprus 49 | Germany 50 | Italy 51 | Ireland 52 | *) 53 | 54 | #r "nuget: Google.OrTools, Version=9.7.2996" 55 | open Google.OrTools.LinearSolver 56 | 57 | // NEW: MODIFIED FROM PREVIOUS SCRIPT 58 | // Mixed Integer Linear Programming solver 59 | let solver = Solver.CreateSolver("SCIP") 60 | 61 | // variables: shipments (origin, destination) 62 | // ----------------------------------------------------------------------------- 63 | 64 | type Shipment = { 65 | Origin: string 66 | Destination: string 67 | } 68 | 69 | // we can ship from anywhere to anywhere 70 | let variables = 71 | factories 72 | |> Seq.collect (fun kv -> 73 | let factory = kv.Key 74 | let destinations = 75 | countries 76 | |> Array.map (fun c -> c.Name) 77 | destinations 78 | |> Seq.map (fun country -> 79 | { Origin = factory; Destination = country }, 80 | // not bounded by capacity anymore 81 | solver.MakeNumVar(0.0, infinity, $"{factory}-{country}") 82 | ) 83 | ) 84 | |> Map.ofSeq 85 | 86 | // NEW: MODIFIED FROM PREVIOUS SCRIPT 87 | // variables: how many machines do we have in each factory? 88 | // ----------------------------------------------------------------------------- 89 | 90 | let factorySizes = 91 | factories 92 | |> Map.map (fun name _ -> 93 | solver.MakeIntVar(0, 10, $"SIZE {name}") 94 | ) 95 | 96 | // NEW: MODIFIED FROM PREVIOUS SCRIPT 97 | // production capacity: we can ship only what we have machines for 98 | // sum shipments <= machines * machine capacity 99 | // capacity - shipments >= 0 100 | // ----------------------------------------------------------------------------- 101 | 102 | factories 103 | |> Map.iter (fun factory destinations -> 104 | let c = solver.MakeConstraint($"Capacity {factory}") 105 | c.SetLb(0.0) 106 | 107 | let factorySize = factorySizes.[factory] 108 | c.SetCoefficient(factorySize, machineCapacity) 109 | 110 | // TODO 111 | // Setup the coefficients of the relevant variables, 112 | // so the shipments from the factory are less than the capacity 113 | failwith "TODO" 114 | ) 115 | 116 | // demand constraint 117 | // constraint: each country can receive up to its demand 118 | // ----------------------------------------------------------------------------- 119 | 120 | countries 121 | |> Array.iter (fun country -> 122 | let c = 123 | solver.MakeConstraint( 124 | 0.0, 125 | country.Population, 126 | $"Demand {country}" 127 | ) 128 | variables 129 | |> Map.filter (fun shipment variable -> 130 | shipment.Destination = country.Name 131 | ) 132 | |> Map.iter (fun shipment variable -> 133 | c.SetCoefficient(variable, 1.0) 134 | ) 135 | ) 136 | 137 | // Objective 138 | // We want to maximize profit 139 | // ----------------------------------------------------------------------------- 140 | 141 | let objective = solver.Objective() 142 | objective.SetMaximization() 143 | 144 | // profit 145 | variables 146 | |> Map.iter (fun shipment variable -> 147 | let origin = 148 | countries 149 | |> Array.find (fun x -> x.Name = factoryLocations.[shipment.Origin].Name) 150 | let dest = countries |> Array.find (fun x -> x.Name = shipment.Destination) 151 | let travelDistance = distance origin.Coords dest.Coords 152 | let profitPerUnit = 153 | unitSalePrice 154 | - 155 | travelDistance * transportationCost 156 | objective.SetCoefficient(variable, profitPerUnit) 157 | ) 158 | 159 | // NEW: MODIFIED FROM PREVIOUS SCRIPT 160 | // machine cost 161 | 162 | // TODO: 163 | // each machine installed should cost us machineCost, 164 | // and reduce our profit accordingly 165 | 166 | 167 | // ... and solve 168 | let solution = solver.Solve() 169 | 170 | // How big are the optimal factories? 171 | // Is every country receiving its demand? 172 | -------------------------------------------------------------------------------- /solved/level-2-allocation.fsx: -------------------------------------------------------------------------------- 1 | #load "data.fsx" 2 | open Data 3 | 4 | // 563.0 5 | countries 6 | |> Array.sumBy (fun x -> x.Population) 7 | 8 | // units per factory per unit of time 9 | let capacity = 150.0 10 | 11 | // NEW: MODIFIED FROM PREVIOUS SCRIPT 12 | let unitSalePrice = 1.0 // price per unit sold 13 | // large distance ~ 3000 kms 14 | let transportationCost = 1.0 / 2500. 15 | 16 | // countries served 17 | let factory1 = countries.[ 0 .. 9 ] |> Array.map (fun x -> x.Name) 18 | let factory2 = countries.[ 0 .. 4 ] |> Array.map (fun x -> x.Name) 19 | let factory3 = countries.[ 10 .. ] |> Array.map (fun x -> x.Name) 20 | let factory4 = countries.[ 10 .. 14 ] |> Array.map (fun x -> x.Name) 21 | let factory5 = countries.[ 13 .. 14 ] |> Array.map (fun x -> x.Name) 22 | 23 | let factories = 24 | [ 25 | "FACTORY 1", factory1 26 | "FACTORY 2", factory2 27 | "FACTORY 3", factory3 28 | "FACTORY 4", factory4 29 | "FACTORY 5", factory5 30 | ] 31 | |> Map.ofList 32 | 33 | // NEW: MODIFIED FROM PREVIOUS SCRIPT 34 | // Each factory is located in a country 35 | let factoryLocations = 36 | [ 37 | "FACTORY 1", countries.[0] 38 | "FACTORY 2", countries.[4] 39 | "FACTORY 3", countries.[10] 40 | "FACTORY 4", countries.[14] 41 | "FACTORY 5", countries.[13] 42 | ] 43 | |> Map.ofList 44 | 45 | #r "nuget: Google.OrTools, Version=9.7.2996" 46 | open Google.OrTools.LinearSolver 47 | 48 | // Pure Linear Programming solver 49 | let solver = Solver.CreateSolver("GLOP") 50 | 51 | // variables: shipments (origin, destination) 52 | // ----------------------------------------------------------------------------- 53 | 54 | type Shipment = { 55 | Origin: string 56 | Destination: string 57 | } 58 | 59 | let variables = 60 | factories 61 | |> Seq.collect (fun kv -> 62 | let factory = kv.Key 63 | let destinations = kv.Value 64 | destinations 65 | |> Seq.map (fun country -> 66 | { Origin = factory; Destination = country }, 67 | solver.MakeNumVar(0.0, capacity, $"{factory}-{country}") 68 | ) 69 | ) 70 | |> Map.ofSeq 71 | 72 | // production capacity constraint 73 | // constraint: each factory can ship only up to its capacity 74 | // ----------------------------------------------------------------------------- 75 | 76 | factories 77 | |> Map.iter (fun factory destinations -> 78 | let c = solver.MakeConstraint(0.0, capacity, $"Capacity {factory}") 79 | variables 80 | |> Map.filter (fun shipment variable -> 81 | shipment.Origin = factory 82 | ) 83 | |> Map.iter (fun shipment variable -> 84 | c.SetCoefficient(variable, 1.0) 85 | ) 86 | ) 87 | 88 | // demand constraint 89 | // constraint: each country can receive up to its demand 90 | // ----------------------------------------------------------------------------- 91 | 92 | countries 93 | |> Array.iter (fun country -> 94 | let c = 95 | solver.MakeConstraint( 96 | // NEW: MODIFIED FROM PREVIOUS SCRIPT 97 | 0.0, 98 | country.Population, 99 | $"Demand {country}" 100 | ) 101 | variables 102 | |> Map.filter (fun shipment variable -> 103 | shipment.Destination = country.Name 104 | ) 105 | |> Map.iter (fun shipment variable -> 106 | c.SetCoefficient(variable, 1.0) 107 | ) 108 | ) 109 | 110 | // Objective 111 | // We want to maximize profit 112 | // ----------------------------------------------------------------------------- 113 | 114 | let objective = solver.Objective() 115 | objective.SetMaximization() 116 | 117 | variables 118 | |> Map.iter (fun shipment variable -> 119 | // country where the shipment comes from 120 | let origin = 121 | countries 122 | |> Array.find (fun x -> 123 | x.Name = factoryLocations.[shipment.Origin].Name 124 | ) 125 | // country where the shipment goes to 126 | let dest = 127 | countries 128 | |> Array.find (fun x -> 129 | x.Name = shipment.Destination 130 | ) 131 | let travelDistance = distance origin.Coords dest.Coords 132 | // profit per unit shipped 133 | let profitPerUnit = 134 | unitSalePrice 135 | - 136 | travelDistance * transportationCost 137 | objective.SetCoefficient(variable, profitPerUnit) 138 | ) 139 | 140 | // ... and solve 141 | let solution = solver.Solve() 142 | 143 | // We can observe how big each shipment should be 144 | variables 145 | |> Map.iter (fun k v -> printfn $"{k}: {v.SolutionValue()}") 146 | 147 | // Which factories are fully utilized? Which are barely utilized? 148 | // Are we shipping all we could ship? 149 | // Which countries get / don't get all they wanted? Why? 150 | 151 | variables 152 | |> Seq.groupBy (fun kv -> kv.Key.Destination) 153 | |> Seq.map (fun (k, v) -> 154 | k, 155 | v 156 | |> Seq.sumBy (fun x -> x.Value.SolutionValue()) 157 | ) 158 | |> Seq.toArray 159 | 160 | variables 161 | |> Seq.groupBy (fun kv -> kv.Key.Origin) 162 | |> Seq.map (fun (k, v) -> 163 | k, 164 | v 165 | |> Seq.sumBy (fun x -> x.Value.SolutionValue()) 166 | ) 167 | |> Seq.toArray 168 | 169 | variables 170 | |> Seq.sumBy (fun kv -> kv.Value.SolutionValue()) 171 | 172 | countries 173 | |> Seq.sumBy (fun kv -> kv.Population) 174 | -------------------------------------------------------------------------------- /level-4-traveling-salesman.fsx: -------------------------------------------------------------------------------- 1 | #r "nuget: Google.OrTools, Version=9.7.2996" 2 | open Google.OrTools.LinearSolver 3 | 4 | // MILP 5 | let solver = Solver.CreateSolver("SCIP") 6 | 7 | type LocationID = 8 | | LocationID of string 9 | 10 | type Move = { 11 | Origin: LocationID 12 | Destination: LocationID 13 | } 14 | 15 | // setup 16 | // ----------------------------------------------------------------------------- 17 | 18 | #load "data.fsx" 19 | open Data 20 | 21 | let locations = 22 | countries 23 | |> Array.map (fun c -> c.Capital |> LocationID) 24 | 25 | let n = locations |> Array.length 26 | 27 | // Variables 28 | // For each pair of location, ex Paris -> Berlin, 29 | // we create a boolean that indicates "do we go from Paris to Berlin" 30 | // ----------------------------------------------------------------------------- 31 | 32 | let moves = 33 | [| 34 | for i in 0 .. (n - 1) do 35 | for j in 0 .. (n - 1) do 36 | if i <> j 37 | then 38 | yield 39 | { 40 | Origin = locations.[i] 41 | Destination = locations.[j] 42 | }, 43 | solver.MakeBoolVar($"X_{i}_{j}") 44 | 45 | |] 46 | |> Map.ofArray 47 | 48 | // We pre-compute the distance (the cost) of every move 49 | // between any pair of locations. 50 | // ----------------------------------------------------------------------------- 51 | 52 | let costs = 53 | moves 54 | |> Map.map (fun move _ -> 55 | let origin = 56 | countries 57 | |> Array.find (fun x -> LocationID x.Capital = move.Origin) 58 | let dest = 59 | countries 60 | |> Array.find (fun x -> LocationID x.Capital = move.Destination) 61 | let cost = distance origin.Coords dest.Coords 62 | cost 63 | ) 64 | 65 | // constraints 66 | // ----------------------------------------------------------------------------- 67 | 68 | // constraint 1 69 | // every city is visited exactly once: 70 | // each city is entered exactly once. 71 | // ----------------------------------------------------------------------------- 72 | 73 | locations 74 | |> Array.iter (fun location -> 75 | // create constraint 76 | let c = solver.MakeConstraint($"Enter {location}") 77 | c.SetBounds(1.0, 1.0) 78 | moves 79 | |> Map.filter (fun move _ -> move.Destination = location) 80 | // sum = 1 81 | |> Map.iter (fun _ variable -> c.SetCoefficient(variable, 1.0)) 82 | ) 83 | 84 | // constraint 2 85 | // every city is visited exactly once: 86 | // each city is exited exactly once. 87 | // ----------------------------------------------------------------------------- 88 | 89 | // TODO 90 | // Setup the constraints 91 | 92 | 93 | 94 | // constraint 3 95 | // no sub-cycles are allowed (ex: Paris -> Berlin -> Paris) 96 | // ----------------------------------------------------------------------------- 97 | 98 | type Order = | Order of LocationID 99 | 100 | // We create integer variables for locations 2 .. n, 101 | // indicating in which order location X is visited in the circuit. 102 | // ----------------------------------------------------------------------------- 103 | 104 | let orders = 105 | locations 106 | // ignore the first in the list: by convention, starting point 107 | |> Array.skip 1 108 | |> Array.map (fun location -> 109 | Order location, 110 | solver.MakeIntVar(1, n, $"Order Variable {location}") 111 | ) 112 | |> Map.ofArray 113 | 114 | // We setup the following constraint, 115 | // which prevents sub-cycles in the circuit: 116 | // u_i - u_j + (n - 1) * x_i,j <= (n - 2) , for 2 <= i <> j <= n 117 | // https://en.wikipedia.org/wiki/Travelling_salesman_problem#Miller%E2%80%93Tucker%E2%80%93Zemlin_formulation[21] 118 | // ----------------------------------------------------------------------------- 119 | 120 | orders 121 | |> Map.iter (fun origin originVariable -> 122 | orders 123 | |> Map.iter (fun destination destinationVariable -> 124 | let o = match origin with | Order o -> o 125 | let d = match destination with | Order d -> d 126 | if o <> d 127 | then 128 | let c = solver.MakeConstraint($"Cycle {origin} {destination}") 129 | // TODO 130 | // setup the constraint, following this approach: 131 | // https://en.wikipedia.org/wiki/Travelling_salesman_problem#Miller%E2%80%93Tucker%E2%80%93Zemlin_formulation[21] 132 | ignore () 133 | ) 134 | ) 135 | 136 | // objective: we minimize the total distance traveled 137 | // ----------------------------------------------------------------------------- 138 | 139 | let objective = solver.Objective() 140 | moves 141 | |> Map.iter (fun move variable -> 142 | let cost = costs.[move] 143 | objective.SetCoefficient(variable, cost) 144 | ) 145 | 146 | objective.SetMinimization() 147 | 148 | let result = solver.Solve() 149 | 150 | moves 151 | |> Map.iter (fun move variable -> 152 | printfn $"{move}: {variable.SolutionValue()}" 153 | ) 154 | 155 | orders 156 | |> Map.iter (fun order variable -> 157 | printfn $"{order}: {variable.SolutionValue()}") 158 | 159 | orders 160 | |> Seq.sortBy (fun kv -> kv.Value.SolutionValue()) 161 | |> Seq.map (fun kv -> kv.Key) 162 | |> Seq.iter (fun x -> printfn $"{x}") -------------------------------------------------------------------------------- /solved/level-4-traveling-salesman.fsx: -------------------------------------------------------------------------------- 1 | #r "nuget: Google.OrTools, Version=9.7.2996" 2 | open Google.OrTools.LinearSolver 3 | 4 | // MILP 5 | let solver = Solver.CreateSolver("SCIP") 6 | 7 | type LocationID = 8 | | LocationID of string 9 | 10 | type Move = { 11 | Origin: LocationID 12 | Destination: LocationID 13 | } 14 | 15 | // setup 16 | // ----------------------------------------------------------------------------- 17 | 18 | #load "data.fsx" 19 | open Data 20 | 21 | let locations = 22 | countries 23 | |> Array.map (fun c -> c.Capital |> LocationID) 24 | 25 | let n = locations |> Array.length 26 | 27 | // Variables 28 | // For each pair of location, ex Paris -> Berlin, 29 | // we create a boolean that indicates "do we go from Paris to Berlin" 30 | // ----------------------------------------------------------------------------- 31 | 32 | let moves = 33 | [| 34 | for i in 0 .. (n - 1) do 35 | for j in 0 .. (n - 1) do 36 | if i <> j 37 | then 38 | yield 39 | { 40 | Origin = locations.[i] 41 | Destination = locations.[j] 42 | }, 43 | solver.MakeBoolVar($"X_{i}_{j}") 44 | 45 | |] 46 | |> Map.ofArray 47 | 48 | // We pre-compute the distance (the cost) of every move 49 | // between any pair of locations. 50 | // ----------------------------------------------------------------------------- 51 | 52 | let costs = 53 | moves 54 | |> Map.map (fun move _ -> 55 | let origin = 56 | countries 57 | |> Array.find (fun x -> LocationID x.Capital = move.Origin) 58 | let dest = 59 | countries 60 | |> Array.find (fun x -> LocationID x.Capital = move.Destination) 61 | let cost = distance origin.Coords dest.Coords 62 | cost 63 | ) 64 | 65 | // constraints 66 | // ----------------------------------------------------------------------------- 67 | 68 | // constraint 1 69 | // every city is visited exactly once: 70 | // each city is entered exactly once. 71 | // ----------------------------------------------------------------------------- 72 | 73 | locations 74 | |> Array.iter (fun location -> 75 | // create constraint 76 | let c = solver.MakeConstraint($"Enter {location}") 77 | c.SetBounds(1.0, 1.0) 78 | moves 79 | |> Map.filter (fun move _ -> move.Destination = location) 80 | // sum = 1 81 | |> Map.iter (fun _ variable -> c.SetCoefficient(variable, 1.0)) 82 | ) 83 | 84 | // constraint 2 85 | // every city is visited exactly once: 86 | // each city is exited exactly once. 87 | // ----------------------------------------------------------------------------- 88 | 89 | locations 90 | |> Array.iter (fun location -> 91 | // create constraint 92 | let c = solver.MakeConstraint($"Leave {location}") 93 | c.SetBounds(1.0, 1.0) 94 | moves 95 | |> Map.filter (fun move _ -> move.Origin = location) 96 | // sum = 1 97 | |> Map.iter (fun _ variable -> c.SetCoefficient(variable, 1.0)) 98 | ) 99 | 100 | // constraint 3 101 | // no sub-cycles are allowed (ex: Paris -> Berlin -> Paris) 102 | // ----------------------------------------------------------------------------- 103 | 104 | type Order = | Order of LocationID 105 | 106 | // We create integer variables for locations 2 .. n, 107 | // indicating in which order location X is visited in the circuit. 108 | // ----------------------------------------------------------------------------- 109 | 110 | let orders = 111 | locations 112 | // ignore the first in the list: by convention, starting point 113 | |> Array.skip 1 114 | |> Array.map (fun location -> 115 | Order location, 116 | solver.MakeIntVar(1, n, $"Order Variable {location}") 117 | ) 118 | |> Map.ofArray 119 | 120 | // We setup the following constraint, 121 | // which prevents sub-cycles in the circuit: 122 | // u_i - u_j + (n - 1) * x_i,j <= (n - 2) , 2 <= i <> j <= n 123 | // ----------------------------------------------------------------------------- 124 | 125 | orders 126 | |> Map.iter (fun origin originVariable -> 127 | orders 128 | |> Map.iter (fun destination destinationVariable -> 129 | let o = match origin with | Order o -> o 130 | let d = match destination with | Order d -> d 131 | if o <> d 132 | then 133 | let c = solver.MakeConstraint($"Cycle {origin} {destination}") 134 | 135 | c.SetCoefficient(originVariable, 1) 136 | c.SetCoefficient(destinationVariable, -1) 137 | 138 | c.SetCoefficient(moves.[ { Origin = o; Destination = d } ], float (n - 1)) 139 | c.SetUb(float (n - 2)) 140 | ) 141 | ) 142 | 143 | // objective: we minimize the total distance traveled 144 | // ----------------------------------------------------------------------------- 145 | 146 | let objective = solver.Objective() 147 | moves 148 | |> Map.iter (fun move variable -> 149 | let cost = costs.[move] 150 | objective.SetCoefficient(variable, cost) 151 | ) 152 | 153 | objective.SetMinimization() 154 | 155 | let result = solver.Solve() 156 | 157 | moves 158 | |> Map.iter (fun move variable -> 159 | printfn $"{move}: {variable.SolutionValue()}" 160 | ) 161 | 162 | orders 163 | |> Map.iter (fun order variable -> 164 | printfn $"{order}: {variable.SolutionValue()}") 165 | 166 | orders 167 | |> Seq.sortBy (fun kv -> kv.Value.SolutionValue()) 168 | |> Seq.map (fun kv -> kv.Key) 169 | |> Seq.iter (fun x -> printfn $"{x}") -------------------------------------------------------------------------------- /solved/level-3-distribution.fsx: -------------------------------------------------------------------------------- 1 | #load "data.fsx" 2 | open Data 3 | 4 | // 563.0 5 | countries 6 | |> Array.sumBy (fun x -> x.Population) 7 | 8 | // fixed capacity is gone 9 | // let capacity = 200.0 10 | 11 | // NEW: MODIFIED FROM PREVIOUS SCRIPT 12 | let machineCapacity = 50.0 13 | // NEW: MODIFIED FROM PREVIOUS SCRIPT 14 | let machineCost = 10.0 15 | let unitSalePrice = 1.0 // price per unit sold 16 | // large distance ~ 3000 kms 17 | let transportationCost = 1.0 / 2500. 18 | 19 | // countries served 20 | let factory1 = countries |> Array.map (fun x -> x.Name) 21 | let factory2 = countries |> Array.map (fun x -> x.Name) 22 | let factory3 = countries |> Array.map (fun x -> x.Name) 23 | let factory4 = countries |> Array.map (fun x -> x.Name) 24 | let factory5 = countries |> Array.map (fun x -> x.Name) 25 | 26 | let factories = 27 | [ 28 | "FACTORY 1", factory1 29 | "FACTORY 2", factory2 30 | "FACTORY 3", factory3 31 | "FACTORY 4", factory4 32 | "FACTORY 5", factory5 33 | ] 34 | |> Map.ofList 35 | 36 | let factoryLocations = 37 | [ 38 | "FACTORY 1", countries.[0] 39 | "FACTORY 2", countries.[4] 40 | "FACTORY 3", countries.[10] 41 | "FACTORY 4", countries.[14] 42 | "FACTORY 5", countries.[13] 43 | ] 44 | |> Map.ofList 45 | 46 | (* 47 | Austria 48 | Cyprus 49 | Germany 50 | Italy 51 | Ireland 52 | *) 53 | 54 | #r "nuget: Google.OrTools, Version=9.7.2996" 55 | open Google.OrTools.LinearSolver 56 | 57 | // NEW: MODIFIED FROM PREVIOUS SCRIPT 58 | // Mixed Integer Linear Programming solver 59 | let solver = Solver.CreateSolver("SCIP") 60 | 61 | // variables: shipments (origin, destination) 62 | // ----------------------------------------------------------------------------- 63 | 64 | type Shipment = { 65 | Origin: string 66 | Destination: string 67 | } 68 | 69 | // we can ship from anywhere to anywhere 70 | let variables = 71 | factories 72 | |> Seq.collect (fun kv -> 73 | let factory = kv.Key 74 | let destinations = 75 | countries 76 | |> Array.map (fun c -> c.Name) 77 | destinations 78 | |> Seq.map (fun country -> 79 | { Origin = factory; Destination = country }, 80 | // not bounded by capacity anymore 81 | solver.MakeNumVar(0.0, infinity, $"{factory}-{country}") 82 | ) 83 | ) 84 | |> Map.ofSeq 85 | 86 | // NEW: MODIFIED FROM PREVIOUS SCRIPT 87 | // variables: how many machines do we have in each factory? 88 | // ----------------------------------------------------------------------------- 89 | 90 | let factorySizes = 91 | factories 92 | |> Map.map (fun name _ -> 93 | solver.MakeIntVar(0, 10, $"SIZE {name}") 94 | ) 95 | 96 | // NEW: MODIFIED FROM PREVIOUS SCRIPT 97 | // production capacity: we can ship only what we have machines for 98 | // sum shipments <= machines * machine capacity 99 | // capacity - shipments >= 0 100 | // ----------------------------------------------------------------------------- 101 | 102 | factories 103 | |> Map.iter (fun factory destinations -> 104 | let c = solver.MakeConstraint($"Capacity {factory}") 105 | c.SetLb(0.0) 106 | 107 | let factorySize = factorySizes.[factory] 108 | c.SetCoefficient(factorySize, machineCapacity) 109 | 110 | variables 111 | |> Map.filter (fun shipment variable -> 112 | shipment.Origin = factory 113 | ) 114 | |> Map.iter (fun shipment variable -> 115 | c.SetCoefficient(variable, -1.0) 116 | ) 117 | ) 118 | 119 | // demand constraint 120 | // constraint: each country can receive up to its demand 121 | // ----------------------------------------------------------------------------- 122 | 123 | countries 124 | |> Array.iter (fun country -> 125 | let c = 126 | solver.MakeConstraint( 127 | 0.0, 128 | country.Population, 129 | $"Demand {country}" 130 | ) 131 | variables 132 | |> Map.filter (fun shipment variable -> 133 | shipment.Destination = country.Name 134 | ) 135 | |> Map.iter (fun shipment variable -> 136 | c.SetCoefficient(variable, 1.0) 137 | ) 138 | ) 139 | 140 | 141 | // Objective 142 | // We want to maximize profit 143 | // ----------------------------------------------------------------------------- 144 | 145 | let objective = solver.Objective() 146 | objective.SetMaximization() 147 | 148 | // profit 149 | variables 150 | |> Map.iter (fun shipment variable -> 151 | let origin = 152 | countries 153 | |> Array.find (fun x -> x.Name = factoryLocations.[shipment.Origin].Name) 154 | let dest = countries |> Array.find (fun x -> x.Name = shipment.Destination) 155 | let travelDistance = distance origin.Coords dest.Coords 156 | let profitPerUnit = 157 | unitSalePrice 158 | - 159 | travelDistance * transportationCost 160 | objective.SetCoefficient(variable, profitPerUnit) 161 | ) 162 | 163 | // NEW: MODIFIED FROM PREVIOUS SCRIPT 164 | // machine cost 165 | factorySizes 166 | |> Map.iter (fun factory size -> 167 | objective.SetCoefficient(size, - machineCost) 168 | ) 169 | 170 | // ... and solve 171 | let solution = solver.Solve() 172 | 173 | factorySizes 174 | |> Map.iter (fun factory size -> 175 | printfn $"{factory}: {size.SolutionValue()}" 176 | ) 177 | 178 | variables 179 | |> Map.iter (fun k v -> printfn $"{k}: {v.SolutionValue()}") 180 | 181 | variables 182 | |> Seq.groupBy (fun kv -> kv.Key.Destination) 183 | |> Seq.map (fun (k, v) -> 184 | k, 185 | v 186 | |> Seq.sumBy (fun x -> x.Value.SolutionValue()) 187 | ) 188 | |> Seq.toArray 189 | 190 | variables 191 | |> Seq.groupBy (fun kv -> kv.Key.Origin) 192 | |> Seq.map (fun (k, v) -> 193 | k, 194 | v 195 | |> Seq.sumBy (fun x -> x.Value.SolutionValue()) 196 | ) 197 | |> Seq.toArray 198 | 199 | variables 200 | |> Seq.sumBy (fun kv -> kv.Value.SolutionValue()) 201 | 202 | countries 203 | |> Seq.sumBy (fun kv -> kv.Population) 204 | 205 | variables 206 | |> Seq.groupBy (fun kv -> kv.Key.Origin) 207 | |> Seq.iter (fun (k,kv) -> 208 | printfn $"{k}" 209 | kv 210 | |> Seq.filter (fun x -> x.Value.SolutionValue() > 0.0) 211 | |> Seq.iter (fun x -> printfn $" {x.Key.Destination}") 212 | ) 213 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # ASP.NET Scaffolding 66 | ScaffoldingReadMe.txt 67 | 68 | # StyleCop 69 | StyleCopReport.xml 70 | 71 | # Files built by Visual Studio 72 | *_i.c 73 | *_p.c 74 | *_h.h 75 | *.ilk 76 | *.meta 77 | *.obj 78 | *.iobj 79 | *.pch 80 | *.pdb 81 | *.ipdb 82 | *.pgc 83 | *.pgd 84 | *.rsp 85 | *.sbr 86 | *.tlb 87 | *.tli 88 | *.tlh 89 | *.tmp 90 | *.tmp_proj 91 | *_wpftmp.csproj 92 | *.log 93 | *.tlog 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio 6 auto-generated project file (contains which files were open etc.) 298 | *.vbp 299 | 300 | # Visual Studio 6 workspace and project file (working project files containing files to include in project) 301 | *.dsw 302 | *.dsp 303 | 304 | # Visual Studio 6 technical files 305 | *.ncb 306 | *.aps 307 | 308 | # Visual Studio LightSwitch build output 309 | **/*.HTMLClient/GeneratedArtifacts 310 | **/*.DesktopClient/GeneratedArtifacts 311 | **/*.DesktopClient/ModelManifest.xml 312 | **/*.Server/GeneratedArtifacts 313 | **/*.Server/ModelManifest.xml 314 | _Pvt_Extensions 315 | 316 | # Paket dependency manager 317 | .paket/paket.exe 318 | paket-files/ 319 | 320 | # FAKE - F# Make 321 | .fake/ 322 | 323 | # CodeRush personal settings 324 | .cr/personal 325 | 326 | # Python Tools for Visual Studio (PTVS) 327 | __pycache__/ 328 | *.pyc 329 | 330 | # Cake - Uncomment if you are using it 331 | # tools/** 332 | # !tools/packages.config 333 | 334 | # Tabs Studio 335 | *.tss 336 | 337 | # Telerik's JustMock configuration file 338 | *.jmconfig 339 | 340 | # BizTalk build output 341 | *.btp.cs 342 | *.btm.cs 343 | *.odx.cs 344 | *.xsd.cs 345 | 346 | # OpenCover UI analysis results 347 | OpenCover/ 348 | 349 | # Azure Stream Analytics local run output 350 | ASALocalRun/ 351 | 352 | # MSBuild Binary and Structured Log 353 | *.binlog 354 | 355 | # NVidia Nsight GPU debugger configuration file 356 | *.nvuser 357 | 358 | # MFractors (Xamarin productivity tool) working folder 359 | .mfractor/ 360 | 361 | # Local History for Visual Studio 362 | .localhistory/ 363 | 364 | # Visual Studio History (VSHistory) files 365 | .vshistory/ 366 | 367 | # BeatPulse healthcheck temp database 368 | healthchecksdb 369 | 370 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 371 | MigrationBackup/ 372 | 373 | # Ionide (cross platform F# VS Code tools) working folder 374 | .ionide/ 375 | 376 | # Fody - auto-generated XML schema 377 | FodyWeavers.xsd 378 | 379 | # VS Code files for those working on multiple tools 380 | .vscode/* 381 | !.vscode/settings.json 382 | !.vscode/tasks.json 383 | !.vscode/launch.json 384 | !.vscode/extensions.json 385 | *.code-workspace 386 | 387 | # Local History for Visual Studio Code 388 | .history/ 389 | 390 | # Windows Installer files from build outputs 391 | *.cab 392 | *.msi 393 | *.msix 394 | *.msm 395 | *.msp 396 | 397 | # JetBrains Rider 398 | *.sln.iml 399 | --------------------------------------------------------------------------------