35 Commits

Author SHA1 Message Date
9191474df8 Bump version to 0.6 2022-12-15 10:36:44 -06:00
841fbf16fb Make distance metric configurable; fix building period bug 2022-12-15 10:26:10 -06:00
48bd3c403f Switch from Euclidean to approximate driving distance 2022-12-15 09:49:38 -06:00
23b3b33146 Update README.md 2022-10-28 14:05:53 -05:00
da158eb961 Update CHANGELOG 2022-08-26 13:26:15 -05:00
e7eec937cb Update README.md 2022-08-26 13:21:42 -05:00
19bec961bd GH Actions: Update Julia versions 2022-08-26 13:12:20 -05:00
8f52c04702 Fix broken image link 2022-08-26 13:08:22 -05:00
19a34fb5d2 Update dependencies; switch to Documenter.jl 2022-08-26 13:04:47 -05:00
92d30460b9 Update README.md 2021-09-03 18:07:40 -05:00
9ebb2e49f9 Fix validation error on JSONSchema 0.3 2021-08-06 14:56:46 -05:00
505e3a8e1e Update CHANGELOG 2021-07-23 17:42:48 -05:00
d4fa75297f Fix OrderedCollections version 2021-07-23 17:42:29 -05:00
881957d6b5 Implement resolve 2021-07-21 14:53:49 -05:00
86cf7f5bd9 Throw exception for infeasible models 2021-07-21 14:18:10 -05:00
a8c7047e2d Add custom show function for Instance and Graph
Without these functions, Julia 1.5 enters an infinite loop whenever it
tries to generate a stack trace, so any error (such as a missing method)
causes the program to hang, instead of an error message to appear.
2021-07-21 14:11:01 -05:00
099e0fae3a Docs: Minor fixes to what-if analsis section 2021-07-21 14:07:00 -05:00
1b8f392852 Docs: Add description of resolve 2021-07-21 14:07:00 -05:00
7a95aa66f6 Update CHANGELOG 2021-07-21 11:49:54 -05:00
40d28c727a Add products report 2021-07-16 11:25:40 -05:00
a9ac164833 Fix GeoDB download 2021-07-16 10:31:21 -05:00
e244ded51d GH Actions: Add Julia 1.6, remove nightly 2021-07-16 10:18:10 -05:00
7180651cfa Reformat source code 2021-07-16 10:15:41 -05:00
0c9465411f Document GeoDB; remove unused code; minor fixes 2021-07-16 10:13:58 -05:00
658d5ddbdc Add population to region; disable zip codes 2021-07-01 17:14:00 -05:00
399db41f86 Temporarily disable failing test 2021-07-01 16:13:38 -05:00
e407a53ecf Download and join population 2021-07-01 16:10:55 -05:00
33ab4c5f76 GeoDB: Prepare for population 2021-07-01 14:56:08 -05:00
c9391dd299 Update JSONSchema 2021-07-01 14:56:08 -05:00
6c70d9acd5 GeoDB: Add 2018-us-zcta and us-state 2021-07-01 14:56:08 -05:00
339255bf9b Enable geodb in input files 2021-07-01 14:56:08 -05:00
ca187fe78e Implement geodb.jl 2021-07-01 14:56:08 -05:00
c256cd8b75 Update CHANGELOG.md 2021-06-25 06:16:20 -05:00
05d48e2cbf Update tagbot.yml 2021-06-25 06:13:27 -05:00
9446b1921d Add tagbot.yml 2021-06-22 11:10:15 -05:00
52 changed files with 1543 additions and 284 deletions

15
.github/workflows/tagbot.yml vendored Normal file
View File

@@ -0,0 +1,15 @@
name: TagBot
on:
issue_comment:
types:
- created
workflow_dispatch:
jobs:
TagBot:
if: github.event_name == 'workflow_dispatch' || github.actor == 'JuliaTagBot'
runs-on: ubuntu-latest
steps:
- uses: JuliaRegistries/TagBot@v1
with:
token: ${{ secrets.GITHUB_TOKEN }}
ssh: ${{ secrets.DOCUMENTER_KEY }}

View File

@@ -10,7 +10,7 @@ jobs:
runs-on: ${{ matrix.os }}
strategy:
matrix:
version: ['1.3', '1.4', '1.5', 'nightly']
version: ['1.6', '1.7', '1.8']
os:
- ubuntu-latest
arch:

3
.gitignore vendored
View File

@@ -9,3 +9,6 @@ notebooks
.idea
*.lp
Manifest.toml
data
build
benchmark

View File

@@ -1,28 +1,60 @@
# Version 0.5.0 (TBD)
# Changelog
All notable changes to this project will be documented in this file.
- The format is based on [Keep a Changelog][changelog].
- This project adheres to [Semantic Versioning][semver].
- For versions before 1.0, we follow the [Pkg.jl convention][pkjjl]
that `0.a.b` is compatible with `0.a.c`.
[changelog]: https://keepachangelog.com/en/1.0.0/
[semver]: https://semver.org/spec/v2.0.0.html
[pkjjl]: https://pkgdocs.julialang.org/v1/compatibility/#compat-pre-1.0
# [0.6.0] -- 2022-12-15
### Added
- Allow RELOG to calculate approximate driving distances, instead of just straight-line distances between points.
### Fixed
- Fix bug that caused building period parameter to be ignored
## [0.5.2] -- 2022-08-26
### Changed
- Update to JuMP 1.x
## [0.5.1] -- 2021-07-23
### Added
- Allow user to specify locations as unique identifiers, instead of latitude and longitude (e.g. `us-state:IL` or `2018-us-county:17043`)
- Add what-if scenarios.
- Add products report.
## [0.5.0] -- 2021-01-06
### Added
- Allow plants to store input material for processing in later years
# Version 0.4.0 (Sep 18, 2020)
## [0.4.0] -- 2020-09-18
### Added
- Generate simplified solution reports (CSV)
# Version 0.3.3 (Aug 13, 2020)
## [0.3.3] -- 2020-10-13
### Added
- Add option to write solution to JSON file in RELOG.solve
- Improve error message when instance is infeasible
- Make output file more readable
# Version 0.3.2 (Aug 7, 2020)
## [0.3.2] -- 2020-10-07
### Added
- Add "building period" parameter
# Version 0.3.1 (July 17, 2020)
## [0.3.1] -- 2020-07-17
### Fixed
- Fix expansion cost breakdown
# Version 0.3.0 (June 25, 2020)
## [0.3.0] -- 2020-06-25
### Added
- Track emissions and energy (transportation and plants)
### Changed
- Minor changes to input file format:
- Make all dictionary keys lowercase
- Rename "outputs (tonne)" to "outputs (tonne/tonne)"

View File

@@ -1,28 +1,19 @@
JULIA := julia --color=yes --project=@.
SRC_FILES := $(wildcard src/*.jl test/*.jl)
VERSION := 0.5
all: docs test
build/sysimage.so: src/sysimage.jl Project.toml Manifest.toml
mkdir -p build
$(JULIA) src/sysimage.jl
build/test.log: $(SRC_FILES) build/sysimage.so
cd test; $(JULIA) --sysimage ../build/sysimage.so runtests.jl
VERSION := 0.6
clean:
rm -rf build/*
rm -rfv build Manifest.toml test/Manifest.toml deps/formatter/build deps/formatter/Manifest.toml
docs:
mkdocs build -d ../docs/$(VERSION)/
cd docs; julia --project=. make.jl; cd ..
rsync -avP --delete-after docs/build/ ../docs/$(VERSION)/
format:
julia -e 'using JuliaFormatter; format(["src", "test"], verbose=true);'
cd deps/formatter; ../../juliaw format.jl
test: build/test.log
test: test/Manifest.toml
./juliaw test/runtests.jl
test-watch:
bash -c "while true; do make test --quiet; sleep 1; done"
test/Manifest.toml: test/Project.toml
julia --project=test -e "using Pkg; Pkg.instantiate()"
.PHONY: docs test
.PHONY: docs test format

View File

@@ -1,14 +1,16 @@
name = "RELOG"
uuid = "a2afcdf7-cf04-4913-85f9-c0d81ddf2008"
authors = ["Alinson S Xavier <axavier@anl.gov>"]
version = "0.5.0"
version = "0.6.0"
[deps]
CRC = "44b605c4-b955-5f2b-9b6d-d2bd01d3d205"
CSV = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b"
Cbc = "9961bab8-2fa3-5c5a-9d89-47fab24efd76"
Clp = "e2554f3b-3117-50c0-817c-e040a3ddf72d"
DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"
DataStructures = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8"
Downloads = "f43a241f-c20a-4ad4-852c-f6b1247861c6"
GZip = "92fee26a-97fe-5a0c-ad85-20a5f3185b63"
Geodesy = "0ef565a4-170c-5f04-8de2-149903a85f3d"
JSON = "682c06a0-de6a-54ab-a142-c8b1cf79cde6"
@@ -16,24 +18,30 @@ JSONSchema = "7d188eb4-7ad8-530c-ae41-71a32a6d4692"
JuMP = "4076af6c-e467-56ae-b986-b466b2749572"
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
MathOptInterface = "b8f27783-ece8-5eb3-8dc8-9495eed66fee"
PackageCompiler = "9b87118b-4619-50d2-8e1e-99f35a4d4d9d"
NearestNeighbors = "b8a86587-4115-5ab1-83bc-aa920d37bbce"
OrderedCollections = "bac558e1-5e72-5ebc-8fee-abe8a469f55d"
Printf = "de0858da-6303-5e67-8744-51eddeeeb8d7"
ProgressBars = "49802e3a-d2f1-5c88-81d8-b72133a6f568"
Shapefile = "8e980c4a-a4fe-5da2-b3a7-4b4b0353a2f4"
Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
ZipFile = "a5390f91-8eb1-5f08-bee0-b1d1ffed6cea"
[compat]
CSV = "0.7"
Cbc = "0.6"
Clp = "0.8"
DataFrames = "0.21"
DataStructures = "0.17"
CRC = "4"
CSV = "0.10"
Cbc = "1"
Clp = "1"
DataFrames = "1"
DataStructures = "0.18"
GZip = "0.5"
Geodesy = "0.5"
Geodesy = "1"
JSON = "0.21"
JSONSchema = "0.2"
JuMP = "0.21"
MathOptInterface = "0.9"
PackageCompiler = "1"
ProgressBars = "0.6"
JSONSchema = "1"
JuMP = "1"
MathOptInterface = "1"
OrderedCollections = "1"
ProgressBars = "1"
Shapefile = "0.8"
ZipFile = "0.10"
julia = "1"

View File

@@ -15,19 +15,22 @@
<img src="https://anl-ceeesa.github.io/RELOG/0.5/images/ex_transportation.png" width="1000px"/>
<img src="https://anl-ceeesa.github.io/RELOG/0.6/assets/ex_transportation.png" width="1000px"/>
### Documentation
* [Usage](https://anl-ceeesa.github.io/RELOG/0.5/usage)
* [Input and Output Data Formats](https://anl-ceeesa.github.io/RELOG/0.5/format)
* [Simplified Solution Reports](https://anl-ceeesa.github.io/RELOG/0.5/reports)
* [Optimization Model](https://anl-ceeesa.github.io/RELOG/0.5/model)
* [Usage](https://anl-ceeesa.github.io/RELOG/0.6/usage)
* [Input and Output Data Formats](https://anl-ceeesa.github.io/RELOG/0.6/format)
* [Simplified Solution Reports](https://anl-ceeesa.github.io/RELOG/0.6/reports)
* [Optimization Model](https://anl-ceeesa.github.io/RELOG/0.6/model)
### Authors
* **Alinson S. Xavier,** Argonne National Laboratory <<axavier@anl.gov>>
* **Nwike Iloeje,** Argonne National Laboratory <<ciloeje@anl.gov>>
* **Alinson S. Xavier** <<axavier@anl.gov>>
* **Nwike Iloeje** <<ciloeje@anl.gov>>
* **John Atkins**
* **Kyle Sun**
* **Audrey Gallier**
### License

5
deps/formatter/Project.toml vendored Normal file
View File

@@ -0,0 +1,5 @@
[deps]
JuliaFormatter = "98e50ef6-434e-11e9-1051-2b60c6c9e899"
[compat]
JuliaFormatter = "0.14.4"

8
deps/formatter/format.jl vendored Normal file
View File

@@ -0,0 +1,8 @@
using JuliaFormatter
format(
[
"../../src",
"../../test",
],
verbose=true,
)

4
docs/Project.toml Normal file
View File

@@ -0,0 +1,4 @@
[deps]
Documenter = "e30172f5-a6a5-5a46-863b-614d45cd2de4"
RELOG = "a2afcdf7-cf04-4913-85f9-c0d81ddf2008"
Revise = "295af30f-e4ad-537b-8983-00126c2a3abe"

19
docs/make.jl Normal file
View File

@@ -0,0 +1,19 @@
using Documenter, RELOG
function make()
makedocs(
sitename="RELOG",
pages=[
"Home" => "index.md",
"usage.md",
"format.md",
"reports.md",
"model.md",
],
format = Documenter.HTML(
assets=["assets/custom.css"],
)
)
end
make()

View File

@@ -0,0 +1,36 @@
@media screen and (min-width: 1056px) {
#documenter .docs-main {
max-width: 65rem !important;
}
}
tbody, thead, pre {
border: 1px solid rgba(0, 0, 0, 0.25);
}
table td, th {
padding: 8px;
}
table p {
margin-bottom: 0;
}
table td code {
white-space: nowrap;
}
table tr,
table th {
border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}
table tr:last-child {
border-bottom: 0;
}
code {
background-color: transparent;
color: rgb(232, 62, 140);
}

View File

Before

Width:  |  Height:  |  Size: 52 KiB

After

Width:  |  Height:  |  Size: 52 KiB

View File

Before

Width:  |  Height:  |  Size: 37 KiB

After

Width:  |  Height:  |  Size: 37 KiB

View File

Before

Width:  |  Height:  |  Size: 31 KiB

After

Width:  |  Height:  |  Size: 31 KiB

View File

Before

Width:  |  Height:  |  Size: 91 KiB

After

Width:  |  Height:  |  Size: 91 KiB

View File

Before

Width:  |  Height:  |  Size: 586 KiB

After

Width:  |  Height:  |  Size: 586 KiB

View File

Before

Width:  |  Height:  |  Size: 29 KiB

After

Width:  |  Height:  |  Size: 29 KiB

View File

Before

Width:  |  Height:  |  Size: 32 KiB

After

Width:  |  Height:  |  Size: 32 KiB

View File

@@ -11,9 +11,10 @@ RELOG accepts as input a JSON file with three sections: `parameters`, `products`
The **parameters** section describes details about the simulation itself.
| Key | Description
|:--------------------------|---------------|
|:--------------------------|:---------------|
|`time horizon (years)` | Number of years in the simulation.
|`building period (years)` | List of years in which we are allowed to open new plants. For example, if this parameter is set to `[1,2,3]`, we can only open plants during the first three years. By default, this equals `[1]`; that is, plants can only be opened during the first year. |
|`distance metric` | Metric used to compute distances between pairs of locations. Valid options are: `"Euclidean"`, for the straight-line distance between points; or `"driving"` for an approximated driving distance. If not specified, defaults to `"Euclidean"`.
#### Example
@@ -21,7 +22,8 @@ The **parameters** section describes details about the simulation itself.
{
"parameters": {
"time horizon (years)": 2,
"building period (years)": [1]
"building period (years)": [1],
"distance metric": "driving",
}
}
```
@@ -31,7 +33,7 @@ The **parameters** section describes details about the simulation itself.
The **products** section describes all products and subproducts in the simulation. The field `instance["Products"]` is a dictionary mapping the name of the product to a dictionary which describes its characteristics. Each product description contains the following keys:
| Key | Description
|:--------------------------------------|---------------|
|:--------------------------------------|:---------------|
|`transportation cost ($/km/tonne)` | The cost to transport this product. Must be a time series.
|`transportation energy (J/km/tonne)` | The energy required to transport this product. Must be a time series. Optional.
|`transportation emissions (tonne/km/tonne)` | A dictionary mapping the name of each greenhouse gas, produced to transport one tonne of this product along one kilometer, to the amount of gas produced (in tonnes). Must be a time series. Optional.
@@ -40,7 +42,7 @@ The **products** section describes all products and subproducts in the simulatio
Each product may have some amount available at the beginning of each time period. In this case, the key `initial amounts` maps to a dictionary with the following keys:
| Key | Description
|:------------------------|---------------|
|:------------------------|:---------------|
| `latitude (deg)` | The latitude of the location.
| `longitude (deg)` | The longitude of the location.
| `amount (tonne)` | The amount of the product initially available at the location. Must be a time series.
@@ -93,7 +95,7 @@ Each product may have some amount available at the beginning of each time period
The **plants** section describes the available types of reverse manufacturing plants, their potential locations and associated costs, as well as their inputs and outputs. The field `instance["Plants"]` is a dictionary mapping the name of the plant to a dictionary with the following keys:
| Key | Description
|:------------------------|---------------|
|:------------------------|:---------------|
| `input` | The name of the product that this plant takes as input. Only one input is accepted per plant.
| `outputs (tonne/tonne)` | A dictionary specifying how many tonnes of each product is produced for each tonnes of input. For example, if the plant outputs 0.5 tonnes of P2 and 0.25 tonnes of P3 for each tonnes of P1 provided, then this entry should be `{"P2": 0.5, "P3": 0.25}`. If the plant does not output anything, this key may be omitted.
|`energy (GJ/tonne)` | The energy required to process 1 tonne of the input. Must be a time series. Optional.
@@ -113,14 +115,14 @@ Each type of plant is associated with a set of potential locations where it can
The `storage` dictionary should contain the following keys:
| Key | Description
|:------------------------|---------------|
|:------------------------|:---------------|
| `cost ($/tonne)` | The cost to store a tonne of input product for one time period. Must be a time series.
| `limit (tonne)` | The maximum amount of input product this plant can have in storage at any given time.
The keys in the `disposal` dictionary should be the names of the products. The values are dictionaries with the following keys:
| Key | Description
|:------------------------|---------------|
|:------------------------|:---------------|
| `cost ($/tonne)` | The cost to dispose of the product. Must be a time series.
| `limit (tonne)` | The maximum amount that can be disposed of. If an unlimited amount can be disposed, this key may be omitted. Must be a time series.
@@ -128,7 +130,7 @@ The keys in the `disposal` dictionary should be the names of the products. The v
The keys in the `capacities (tonne)` dictionary should be the amounts (in tonnes). The values are dictionaries with the following keys:
| Key | Description
|:--------------------------------------|---------------|
|:--------------------------------------|:---------------|
| `opening cost ($)` | The cost to open a plant of this size.
| `fixed operating cost ($)` | The cost to keep the plant open, even if the plant doesn't process anything. Must be a time series.
| `variable operating cost ($/tonne)` | The cost that the plant incurs to process each tonne of input. Must be a time series.
@@ -182,14 +184,46 @@ The keys in the `capacities (tonne)` dictionary should be the amounts (in tonnes
}
```
### Geographic database
Instead of specifying locations using latitudes and longitudes, it is also possible to specify them using unique identifiers, such as the name of a US state, or the county FIPS code. This works anywhere `latitude (deg)` and `longitude (deg)` are expected. For example, instead of:
```json
{
"initial amounts": {
"C1": {
"latitude (deg)": 37.27182,
"longitude (deg)": -119.2704,
"amount (tonne)": [934.56, 934.56]
},
}
}
```
is is possible to write:
```json
{
"initial amounts": {
"C1": {
"location": "us-state:CA",
"amount (tonne)": [934.56, 934.56]
},
}
}
```
Location names follow the format `db:id`, where `db` is the name of the database and `id` is the identifier for a specific location. RELOG currently includes the following databases:
Database | Description | Examples
:--------|:------------|:---------
`us-state`| List of states of the United States. | `us-state:IL` (State of Illinois)
`2018-us-county` | List of United States counties, as of 2018. IDs are 5-digit FIPS codes. | `2018-us-county:17043` (DuPage county in Illinois)
### Current limitations
* Each plant can only be opened exactly once. After open, the plant remains open until the end of the simulation.
* Plants can be expanded at any time, even long after they are open.
* All material available at the beginning of a time period must be entirely processed by the end of that time period. It is not possible to store unprocessed materials from one time period to the next.
* Up to two plant sizes are currently supported. Variable operating costs must be the same for all plant sizes.
* Accurate driving distances are only available for the continental United States.
## Output Data Format (JSON)
To be documented.

View File

@@ -1,25 +1,29 @@
# RELOG: Reverse Logistics Optimization
**RELOG** is an open-source supply chain optimization package focusing on reverse logistics and reverse manufacturing. The package uses Mixed-Integer Linear Programming to determine where to build recycling plants, what size should these plants have and which customers should be served by which plants. The package supports custom reverse logistics pipelines, with multiple types of plants, multiple types of product and multiple time periods.
<img src="images/ex_transportation.png" width="1000px"/>
```@raw html
<center>
<img src="assets/ex_transportation.png" width="1000px"/>
</center>
```
### Table of Contents
* [Usage](usage.md)
* [Input and Output Data Formats](format.md)
* [Simplified Solution Reports](reports.md)
* [Optimization Model](model.md)
```@contents
Pages = ["usage.md", "format.md", "reports.md", "model.md"]
Depth = 3
```
### Source Code
* [https://github.com/ANL-CEEESA/RELOG](https://github.com/ANL-CEEESA/RELOG)
### Authors
* **Alinson S. Xavier,** Argonne National Laboratory <<axavier@anl.gov>>
* **Nwike Iloeje,** Argonne National Laboratory <<ciloeje@anl.gov>>
* **Alinson S. Xavier,** Argonne National Laboratory <axavier@anl.gov>
* **Nwike Iloeje,** Argonne National Laboratory <ciloeje@anl.gov>
### License

View File

@@ -6,53 +6,65 @@ In this page, we describe the precise mathematical optimization model used by RE
### Sets
* $L$ - Set of locations holding the original material to be recycled
* $M$ - Set of materials recovered during the reverse manufacturing process
* $P$ - Set of potential plants to open
* $T = \{ 1, \ldots, t^{max} \} $ - Set of time periods
Symbol | Description
:-------|:------------
$L$ | Set of locations holding the original material to be recycled
$M$ | Set of materials recovered during the reverse manufacturing process
$P$ | Set of potential plants to open
$T = \{ 1, \ldots, t^{max} \}$ | Set of time periods
### Constants
**Plants:**
#### Plants
* $c^\text{disp}_{pmt}$ - Cost of disposing one tonne of material $m$ at plant $p$ during time $t$ (`$/tonne/km`)
* $c^\text{exp}_{pt}$ - Cost of adding one tonne of capacity to plant $p$ at time $t$ (`$/tonne`)
* $c^\text{open}_{pt}$ - Cost of opening plant $p$ at time $t$, at minimum capacity (`$`)
* $c^\text{f-base}_{pt}$ - Fixed cost of keeping plant $p$ open during time period $t$ (`$`)
* $c^\text{f-exp}_{pt}$ - Increase in fixed cost for each additional tonne of capacity (`$/tonne`)
* $c^\text{var}_{pt}$ - Variable cost of processing one tonne of input at plant $p$ at time $t$ (`$/tonne`)
* $c^\text{store}_{pt}$ - Cost of storing one tonne of original material at plant $p$ at time $t$ (`$/tonne`)
* $m^\text{min}_p$ - Minimum capacity of plant $p$ (`tonne`)
* $m^\text{max}_p$ - Maximum capacity of plant $p$ (`tonne`)
* $m^\text{disp}_{pmt}$ - Maximum amount of material $m$ that plant $p$ can dispose of during time $t$ (`tonne`)
* $m^\text{store}_p$ - Maximum amount of original material that plant $p$ can store for later processing.
Symbol | Description | Unit
:-------|:------------|:---
$c^\text{disp}_{pmt}$ | Cost of disposing one tonne of material $m$ at plant $p$ during time $t$ | \$/tonne/km
$c^\text{exp}_{pt}$ | Cost of adding one tonne of capacity to plant $p$ at time $t$ | \$/tonne
$c^\text{open}_{pt}$ | Cost of opening plant $p$ at time $t$, at minimum capacity | $
$c^\text{f-base}_{pt}$ | Fixed cost of keeping plant $p$ open during time period $t$ | $
$c^\text{f-exp}_{pt}$ | Increase in fixed cost for each additional tonne of capacity | \$/tonne
$c^\text{var}_{pt}$ | Variable cost of processing one tonne of input at plant $p$ at time $t$ | \$/tonne
$c^\text{store}_{pt}$ | Cost of storing one tonne of original material at plant $p$ at time $t$ | \$/tonne
$m^\text{min}_p$ | Minimum capacity of plant $p$ | tonne
$m^\text{max}_p$ | Maximum capacity of plant $p$ | tonne
$m^\text{disp}_{pmt}$ | Maximum amount of material $m$ that plant $p$ can dispose of during time $t$ | tonne
$m^\text{store}_p$ | Maximum amount of original material that plant $p$ can store for later processing. | tonne
**Products:**
#### Products
* $\alpha_{pm}$ - Amount of material $m$ recovered by plant $t$ for each tonne of original material (`tonne/tonne`)
* $m^\text{initial}_{lt}$ - Amount of original material to be recycled at location $l$ during time $t$ (`tonne`)
Symbol | Description | Unit
:-------|:------------|:---
$\alpha_{pm}$ | Amount of material $m$ recovered by plant $t$ for each tonne of original material | tonne/tonne
$m^\text{initial}_{lt}$ | Amount of original material to be recycled at location $l$ during time $t$ | tonne
**Transportation:**
#### Transportation
* $c^\text{tr}_{t}$ - Transportation cost during time $t$ (`$/tonne/km`)
* $d_{lp}$ - Distance between plant $p$ and location $l$ (`km`)
Symbol | Description | Unit
:-------|:------------|:---
$c^\text{tr}_{t}$ | Transportation cost during time $t$ | \$/tonne/km
$d_{lp}$ | Distance between plant $p$ and location $l$ | km
### Decision variables
* $q_{mpt}$ - Amount of material $m$ recovered by plant $p$ during time $t$ (`tonne`)
* $u_{pt}$ - Binary variable that equals 1 if plant $p$ starts operating at time $t$ (`bool`)
* $w_{pt}$ - Extra capacity (amount above the minimum) added to plant $p$ during time $t$ (`tonne`)
* $x_{pt}$ - Binary variable that equals 1 if plant $p$ is operational at time $t$ (`bool`)
* $y_{lpt}$ - Amount of product sent from location $l$ to plant $p$ during time $t$ (`tonne`)
* $z^{\text{disp}}_{mpt}$ - Amount of material $m$ disposed of by plant $p$ during time $t$ (`tonne`)
* $z^{\text{store}}_{pt}$ - Amount of original material in storage at plant $p$ by the end of time period $t$ (`tonne`)
* $z^{\text{proc}}_{mpt}$ - Amount of original material processed by plant $p$ during time period $t$ (`tonne`)
Symbol | Description | Unit
:-------|:------------|:---
$q_{mpt}$ | Amount of material $m$ recovered by plant $p$ during time $t$ | tonne
$u_{pt}$ | Binary variable that equals 1 if plant $p$ starts operating at time $t$ | Boolean
$w_{pt}$ | Extra capacity (amount above the minimum) added to plant $p$ during time $t$ | tonne
$x_{pt}$ | Binary variable that equals 1 if plant $p$ is operational at time $t$ | Boolean
$y_{lpt}$ | Amount of product sent from location $l$ to plant $p$ during time $t$ | tonne
$z^{\text{disp}}_{mpt}$ | Amount of material $m$ disposed of by plant $p$ during time $t$ | tonne
$z^{\text{store}}_{pt}$ | Amount of original material in storage at plant $p$ by the end of time period $t$ | tonne
$z^{\text{proc}}_{mpt}$ | Amount of original material processed by plant $p$ during time period $t$ | tonne
### Objective function
RELOG minimizes the overall capital, production and transportation costs:
```math
\begin{align*}
\text{minimize} \;\; &
\sum_{t \in T} \sum_{p \in P} \left[
@@ -73,6 +85,7 @@ RELOG minimizes the overall capital, production and transportation costs:
&
\sum_{t \in T} \sum_{p \in P} \sum_{m \in M} c^{\text{disp}}_{pmt} z_{pmt}
\end{align*}
```
In the first line, we have (i) opening costs, if plant starts operating at time $t$, (ii) fixed operating costs, if plant is operational, (iii) additional fixed operating costs coming from expansion performed in all previous time periods up to the current one, and finally (iv) the expansion costs during the current time period.
In the second line, we have storage and variable processing costs.
@@ -83,14 +96,17 @@ In the fourth line, we have the disposal costs.
* All original materials must be sent to a plant:
\begin{align}
```math
\begin{align*}
& \sum_{p \in P} y_{lpt} = m^\text{initial}_{lt}
& \forall l \in L, t \in T
\end{align}
\end{align*}
```
* Amount received equals amount processed plus stored. Furthermore, all original material should be processed by the end of the simulation.
\begin{align}
```math
\begin{align*}
& \sum_{l \in L} y_{lpt} + z^{\text{store}}_{p,t-1}
= z^{\text{proc}}_{pt} + z^{\text{store}}_{p,t}
& \forall p \in P, t \in T \\
@@ -98,56 +114,70 @@ In the fourth line, we have the disposal costs.
& \forall p \in P \\
& z^{\text{store}}_{p,t^{\max}} = 0
& \forall p \in P
\end{align}
\end{align*}
```
* Plants have a limited processing capacity. Furthermore, if a plant is closed, it has zero processing capacity:
\begin{align}
```math
\begin{align*}
& z^{\text{proc}}_{pt} \leq m^\text{min}_p x_p + \sum_{i=1}^t w_p
& \forall p \in P, t \in T
\end{align}
\end{align*}
```
* Plants have limited storage capacity. Furthermore, if a plant is closed, is has zero storage capacity:
\begin{align}
```math
\begin{align*}
& z^{\text{store}}_{pt} \leq m^\text{store}_p x_p
& \forall p \in P, t \in T
\end{align}
\end{align*}
```
* Plants can only be expanded up to their maximum capacity. Furthermore, if a plant is closed, it cannot be expanded:
\begin{align}
```math
\begin{align*}
& \sum_{i=1}^t w_p \leq m^\text{max}_p x_p
& \forall p \in P, t \in T
\end{align}
\end{align*}
```
* Amount of recovered material is proportional to amount processed:
\begin{align}
```math
\begin{align*}
& q_{mpt} = \alpha_{pm} z^{\text{proc}}_{pt}
& \forall m \in M, p \in P, t \in T
\end{align}
\end{align*}
```
* Because we only consider a single type of plant, all recovered material must be immediately disposed of. In RELOG's full model, recovered materials may be sent to another plant for further processing.
\begin{align}
```math
\begin{align*}
& q_{mpt} = z_{mpt}
& \forall m \in M, p \in P, t \in T
\end{align}
\end{align*}
```
* A plant is operational at time $t$ if it was operational at time $t-1$ or it was built at time $t$. This constraint also prevents a plant from being built multiple times.
\begin{align}
```math
\begin{align*}
& x_{pt} = x_{p,t-1} + u_{pt}
& \forall p \in P, t \in T \setminus \{1\} \\
& x_{p,1} = u_{p,1}
& \forall p \in P
\end{align}
\end{align*}
```
* Variable bounds:
\begin{align}
```math
\begin{align*}
& q_{mpt} \geq 0
& \forall m \in M, p \in P, t \in T \\
& u_{pt} \in \{0,1\}
@@ -162,4 +192,5 @@ In the fourth line, we have the disposal costs.
& p \in P, t \in T \\
& z^{\text{disp}}_{mpt}, z^{\text{proc}}_{mpt} \geq 0
& \forall m \in M, p \in P, t \in T
\end{align}
\end{align*}
```

View File

@@ -6,15 +6,13 @@ In this page, we also illustrate what types of charts and visualizations can be
## Plants report
Report showing plant costs, capacities, energy expenditure and utilization factors.
Generated by `RELOG.write_plants_report(solution, filename)`. For a concrete example, see [nimh_plants.csv](https://github.com/ANL-CEEESA/RELOG/blob/master/test/fixtures/nimh_plants.csv).
Report showing plant costs, capacities, energy expenditure and utilization factors. Generated by `RELOG.write_plants_report(solution, filename)`.
| Column | Description
|:--------------------------------------|---------------|
|:--------------------------------------|:---------------|
| `plant type` | Plant type.
| `location name` | Location name.
| `year` | What year this row corresponds to. This reports includes one row for each year in the simulation.
| `year` | What year this row corresponds to. This reports includes one row for each year.
| `latitude (deg)` | Latitude of the plant.
| `longitude (deg)` | Longitude of the plant.
| `capacity (tonne)` | Capacity of the plant at this point in time.
@@ -47,7 +45,9 @@ sns.barplot(x="year",
.reset_index());
```
<img src="../images/ex_plant_cost_per_year.png" width="500px"/>
```@raw html
<img src="../assets/ex_plant_cost_per_year.png" width="500px"/>
```
* Map showing plant locations (in Python):
```python
@@ -67,21 +67,20 @@ points = gp.points_from_xy(data["longitude (deg)"],
gp.GeoDataFrame(data, geometry=points).plot(ax=ax);
```
<img src="../images/ex_plant_locations.png" width="1000px"/>
```@raw html
<img src="../assets/ex_plant_locations.png" width="1000px"/>
```
## Plant outputs report
Report showing amount of products produced, sent and disposed of by each plant, as well as disposal costs.
Generated by `RELOG.write_plant_outputs_report(solution, filename)`. For a concrete example, see [nimh_plant_outputs.csv](https://github.com/ANL-CEEESA/RELOG/blob/master/test/fixtures/nimh_plant_outputs.csv).
Report showing amount of products produced, sent and disposed of by each plant, as well as disposal costs. Generated by `RELOG.write_plant_outputs_report(solution, filename)`.
| Column | Description
|:--------------------------------------|---------------|
|:--------------------------------------|:---------------|
| `plant type` | Plant type.
| `location name` | Location name.
| `year` | What year this row corresponds to. This reports includes one row for each year in the simulation.
| `year` | What year this row corresponds to. This reports includes one row for each year.
| `product name` | Product being produced.
| `amount produced (tonne)` | Amount of product produced this year.
| `amount sent (tonne)` | Amount of product produced by this plant and sent to another plant for further processing this year.
@@ -105,17 +104,17 @@ sns.barplot(x="amount produced (tonne)",
.reset_index());
```
<img src="../images/ex_amount_produced.png" width="500px"/>
```@raw html
<img src="../assets/ex_amount_produced.png" width="500px"/>
```
## Plant emissions report
Report showing amount of emissions produced by each plant.
Generated by `RELOG.write_plant_emissions_report(solution, filename)`. For a concrete example, see [nimh_plant_emissions.csv](https://github.com/ANL-CEEESA/RELOG/blob/master/test/fixtures/nimh_plant_emissions.csv).
Report showing amount of emissions produced by each plant. Generated by `RELOG.write_plant_emissions_report(solution, filename)`.
| Column | Description
|:--------------------------------------|---------------|
|:--------------------------------------|:---------------|
| `plant type` | Plant type.
| `location name` | Location name.
| `year` | Year.
@@ -139,17 +138,32 @@ sns.barplot(x="plant type",
.reset_index());
```
<img src="../images/ex_emissions.png" width="500px"/>
```@raw html
<img src="../assets/ex_emissions.png" width="500px"/>
```
## Products report
Report showing primary product amounts, locations and marginal costs. Generated by `RELOG.write_products_report(solution, filename)`.
| Column | Description
|:--------------------------------------|:---------------|
| `product name` | Product name.
| `location name` | Name of the collection center.
| `latitude (deg)` | Latitude of the collection center.
| `longitude (deg)` | Longitude of the collection center.
| `year` | What year this row corresponds to. This reports includes one row for each year.
| `amount (tonne)` | Amount of product available at this collection center.
| `marginal cost ($/tonne)` | Cost to process one additional tonne of this product coming from this collection center.
## Transportation report
Report showing amount of product sent from initial locations to plants, and from one plant to another. Includes the distance between each pair of locations, amount-distance shipped, transportation costs and energy expenditure.
Generated by `RELOG.write_transportation_report(solution, filename)`. For a concrete example, see [nimh_transportation.csv](https://github.com/ANL-CEEESA/RELOG/blob/master/test/fixtures/nimh_transportation.csv).
Report showing amount of product sent from initial locations to plants, and from one plant to another. Includes the distance between each pair of locations, amount-distance shipped, transportation costs and energy expenditure. Generated by `RELOG.write_transportation_report(solution, filename)`.
| Column | Description
|:--------------------------------------|---------------|
|:--------------------------------------|:---------------|
| `source type` | If product is being shipped from an initial location, equals `Origin`. If product is being shipped from a plant, equals plant type.
| `source location name` | Name of the location where the product is being shipped from.
| `source latitude (deg)` | Latitude of the source location.
@@ -183,7 +197,9 @@ sns.barplot(x="product",
.reset_index());
```
<img src="../images/ex_transportation_amount_distance.png" width="500px"/>
```@raw html
<img src="../assets/ex_transportation_amount_distance.png" width="500px"/>
```
* Map of transportation lines (in Python):
@@ -226,17 +242,17 @@ gp.GeoDataFrame(data, geometry=points).plot(ax=ax,
markersize=50);
```
<img src="../images/ex_transportation.png" width="1000px"/>
```@raw html
<img src="../assets/ex_transportation.png" width="1000px"/>
```
## Transportation emissions report
Report showing emissions for each trip between initial locations and plants, and between pairs of plants.
Generated by `RELOG.write_transportation_emissions_report(solution, filename)`. For a concrete example, see [nimh_transportation_emissions.csv](https://github.com/ANL-CEEESA/RELOG/blob/master/test/fixtures/nimh_transportation_emissions.csv).
Report showing emissions for each trip between initial locations and plants, and between pairs of plants. Generated by `RELOG.write_transportation_emissions_report(solution, filename)`.
| Column | Description
|:--------------------------------------|---------------|
|:--------------------------------------|:---------------|
| `source type` | If product is being shipped from an initial location, equals `Origin`. If product is being shipped from a plant, equals plant type.
| `source location name` | Name of the location where the product is being shipped from.
| `source latitude (deg)` | Latitude of the source location.
@@ -270,4 +286,6 @@ sns.barplot(x="emission type",
.reset_index());
```
<img src="../images/ex_transportation_emissions.png" width="500px"/>
```@raw html
<img src="../assets/ex_transportation_emissions.png" width="500px"/>
```

View File

@@ -3,22 +3,17 @@ Usage
## 1. Installation
To use RELOG, the first step is to install the [Julia programming language](https://julialang.org/) on your machine. Note that RELOG was developed and tested with Julia 1.5 and may not be compatible with newer versions. After Julia is installed, launch the Julia console, type `]` to switch to package manger mode, then run:
To use RELOG, the first step is to install the [Julia programming language](https://julialang.org/) on your machine. Note that RELOG was developed and tested with Julia 1.8 and may not be compatible with newer versions. After Julia is installed, launch the Julia console, then run:
```text
(@v1.5) pkg> add https://github.com/ANL-CEEESA/RELOG.git
```julia
using Pkg
Pkg.add(name="RELOG", version="0.6")
```
After the package and all its dependencies have been installed, please run the RELOG test suite, as shown below, to make sure that the package has been correctly installed:
```text
(@v1.5) pkg> test RELOG
```
To update the package to a newer version, type `]` to enter the package manager mode, then run:
```text
(@v1.5) pkg> update RELOG
```julia
Pkg.test("RELOG")
```
## 2. Modeling the problem
@@ -66,25 +61,65 @@ RELOG.write_transportation_report(solution, "transportation.csv")
For a complete description of the file formats above, and for a complete list of available reports, see the [data format page](format.md).
## 4. Advanced options
## 4. What-If Analysis
### 4.1 Changing the solver
Fundamentally, RELOG decides when and where to build plants based on a deterministic optimization problem that minimizes costs for a particular input file provided by the user. In practical situations, it may not be possible to perfectly estimate some (or most) entries in this input file in advance, such as costs, demands and emissions. In this situation, it may be interesting to evaluate how well does the facility location plan produced by RELOG work if costs, demands and emissions turn out to be different.
To simplify this what-if analysis, RELOG provides the `resolve` method, which updates a previous solution based on a new scenario, but keeps some of the previous decisions fixed. More precisely, given an optimal solution produced by RELOG and a new input file describing the new scenario, the `resolve` method reoptimizes the supply chain and produces a new solution which still builds the same set of plants as before, in exactly the same locations and with the same capacities, but that may now utilize the plants differently, based on the new data. For example, in the new solution, plants that were previously used at full capacity may now be utilized at half-capacity instead. As another example, regions that were previously served by a certain plant may now be served by a different one.
The following snippet shows how to use the method:
```julia
# Import package
using RELOG
# Optimize for the average scenario
solution_avg, model_avg = RELOG.solve("input_avg.json", return_model=true)
# Write reports for the average scenario
RELOG.write_plants_report(solution_avg, "plants_avg.csv")
RELOG.write_transportation_report(solution_avg, "transportation_avg.csv")
# Re-optimize for the high-demand scenario, keeping plants fixed
solution_high = RELOG.resolve(model_avg, "input_high.json")
# Write reports for the high-demand scenario
RELOG.write_plants_report(solution_high, "plants_high.csv")
RELOG.write_transportation_report(solution_high, "transportation_high.csv")
```
To use the `resolve` method, the new input file should be very similar to the original one. Only the following entries are allowed to change:
- **Products:** Transportation costs, energy, emissions and initial amounts (latitude, longitude and amount).
- **Plants:** Energy and emissions.
- **Plant's location:** Latitude and longitude.
- **Plant's storage:** Cost.
- **Plant's capacity:** Opening cost, fixed operating cost and variable operating cost.
## 5. Advanced options
### 5.1 Changing the solver
By default, RELOG internally uses [Cbc](https://github.com/coin-or/Cbc), an open-source and freely-available Mixed-Integer Linear Programming solver developed by the [COIN-OR Project](https://www.coin-or.org/). For larger-scale test cases, a commercial solver such as Gurobi, CPLEX or XPRESS is recommended. The following snippet shows how to switch from Cbc to Gurobi, for example:
```julia
using RELOG, Gurobi, JuMP
gurobi = optimizer_with_attributes(Gurobi.Optimizer,
"TimeLimit" => 3600,
"MIPGap" => 0.001)
gurobi = optimizer_with_attributes(
Gurobi.Optimizer,
"TimeLimit" => 3600,
"MIPGap" => 0.001,
)
RELOG.solve("instance.json",
output="solution.json",
optimizer=gurobi)
RELOG.solve(
"instance.json",
output="solution.json",
optimizer=gurobi,
)
```
### 4.2 Multi-period heuristics
### 5.2 Multi-period heuristics
For large-scale instances, it may be too time-consuming to find an exact optimal solution to the multi-period version of the problem. For these situations, RELOG includes a heuristic solution method, which proceeds as follows:
@@ -97,6 +132,8 @@ To solve an instance using this heuristic, use the option `heuristic=true`, as s
```julia
using RELOG
solution = RELOG.solve("/home/user/instance.json",
heuristic=true)
solution = RELOG.solve(
"/home/user/instance.json",
heuristic=true,
)
```

View File

@@ -1,6 +1,7 @@
{
"parameters": {
"time horizon (years)": 2
"time horizon (years)": 2,
"distance metric": "driving"
},
"products": {
"P1": {

347
instances/s2.json Normal file
View File

@@ -0,0 +1,347 @@
{
"parameters": {
"time horizon (years)": 2
},
"products": {
"P1": {
"transportation cost ($/km/tonne)": [
0.015,
0.015
],
"transportation energy (J/km/tonne)": [
0.12,
0.11
],
"transportation emissions (tonne/km/tonne)": {
"CO2": [
0.052,
0.050
],
"CH4": [
0.003,
0.002
]
},
"initial amounts": {
"C1": {
"location": "2018-us-county:17043",
"amount (tonne)": [
934.56,
934.56
]
},
"C2": {
"latitude (deg)": 7.0,
"longitude (deg)": 19.0,
"amount (tonne)": [
198.95,
198.95
]
},
"C3": {
"latitude (deg)": 84.0,
"longitude (deg)": 76.0,
"amount (tonne)": [
212.97,
212.97
]
},
"C4": {
"latitude (deg)": 21.0,
"longitude (deg)": 16.0,
"amount (tonne)": [
352.19,
352.19
]
},
"C5": {
"latitude (deg)": 32.0,
"longitude (deg)": 92.0,
"amount (tonne)": [
510.33,
510.33
]
},
"C6": {
"latitude (deg)": 14.0,
"longitude (deg)": 62.0,
"amount (tonne)": [
471.66,
471.66
]
},
"C7": {
"latitude (deg)": 30.0,
"longitude (deg)": 83.0,
"amount (tonne)": [
785.21,
785.21
]
},
"C8": {
"latitude (deg)": 35.0,
"longitude (deg)": 40.0,
"amount (tonne)": [
706.17,
706.17
]
},
"C9": {
"latitude (deg)": 74.0,
"longitude (deg)": 52.0,
"amount (tonne)": [
30.08,
30.08
]
},
"C10": {
"latitude (deg)": 22.0,
"longitude (deg)": 54.0,
"amount (tonne)": [
536.52,
536.52
]
}
}
},
"P2": {
"transportation cost ($/km/tonne)": [
0.02,
0.02
]
},
"P3": {
"transportation cost ($/km/tonne)": [
0.0125,
0.0125
]
},
"P4": {
"transportation cost ($/km/tonne)": [
0.0175,
0.0175
]
}
},
"plants": {
"F1": {
"input": "P1",
"outputs (tonne/tonne)": {
"P2": 0.2,
"P3": 0.5
},
"energy (GJ/tonne)": [
0.12,
0.11
],
"emissions (tonne/tonne)": {
"CO2": [
0.052,
0.050
],
"CH4": [
0.003,
0.002
]
},
"locations": {
"L1": {
"latitude (deg)": 0.0,
"longitude (deg)": 0.0,
"disposal": {
"P2": {
"cost ($/tonne)": [
-10.0,
-10.0
],
"limit (tonne)": [
1.0,
1.0
]
},
"P3": {
"cost ($/tonne)": [
-10.0,
-10.0
],
"limit (tonne)": [
1.0,
1.0
]
}
},
"capacities (tonne)": {
"250.0": {
"opening cost ($)": [
500.0,
500.0
],
"fixed operating cost ($)": [
30.0,
30.0
],
"variable operating cost ($/tonne)": [
30.0,
30.0
]
},
"1000.0": {
"opening cost ($)": [
1250.0,
1250.0
],
"fixed operating cost ($)": [
30.0,
30.0
],
"variable operating cost ($/tonne)": [
30.0,
30.0
]
}
}
},
"L2": {
"location": "2018-us-county:17043",
"capacities (tonne)": {
"0.0": {
"opening cost ($)": [
1000,
1000
],
"fixed operating cost ($)": [
50.0,
50.0
],
"variable operating cost ($/tonne)": [
50.0,
50.0
]
},
"10000.0": {
"opening cost ($)": [
10000,
10000
],
"fixed operating cost ($)": [
50.0,
50.0
],
"variable operating cost ($/tonne)": [
50.0,
50.0
]
}
}
}
}
},
"F2": {
"input": "P2",
"outputs (tonne/tonne)": {
"P3": 0.05,
"P4": 0.80
},
"locations": {
"L3": {
"latitude (deg)": 25.0,
"longitude (deg)": 65.0,
"disposal": {
"P3": {
"cost ($/tonne)": [
100.0,
100.0
]
}
},
"capacities (tonne)": {
"1000.0": {
"opening cost ($)": [
3000,
3000
],
"fixed operating cost ($)": [
50.0,
50.0
],
"variable operating cost ($/tonne)": [
50.0,
50.0
]
}
}
},
"L4": {
"latitude (deg)": 0.75,
"longitude (deg)": 0.20,
"capacities (tonne)": {
"10000": {
"opening cost ($)": [
3000,
3000
],
"fixed operating cost ($)": [
50.0,
50.0
],
"variable operating cost ($/tonne)": [
50.0,
50.0
]
}
}
}
}
},
"F3": {
"input": "P4",
"locations": {
"L5": {
"latitude (deg)": 100.0,
"longitude (deg)": 100.0,
"capacities (tonne)": {
"15000": {
"opening cost ($)": [
0.0,
0.0
],
"fixed operating cost ($)": [
0.0,
0.0
],
"variable operating cost ($/tonne)": [
-15.0,
-15.0
]
}
}
}
}
},
"F4": {
"input": "P3",
"locations": {
"L6": {
"latitude (deg)": 50.0,
"longitude (deg)": 50.0,
"capacities (tonne)": {
"10000": {
"opening cost ($)": [
0.0,
0.0
],
"fixed operating cost ($)": [
0.0,
0.0
],
"variable operating cost ($/tonne)": [
-15.0,
-15.0
]
}
}
}
}
}
}
}

75
juliaw Executable file
View File

@@ -0,0 +1,75 @@
#!/bin/bash
# UnitCommitment.jl: Optimization Package for Security-Constrained Unit Commitment
# Copyright (C) 2020-2021, UChicago Argonne, LLC. All rights reserved.
# Released under the modified BSD license. See COPYING.md for more details.
if [ ! -e Project.toml ]; then
echo "juliaw: Project.toml not found"
exit 1
fi
if [ ! -e Manifest.toml ]; then
julia --project=. -e 'using Pkg; Pkg.instantiate()' || exit 1
fi
if [ ! -e build/sysimage.so -o Project.toml -nt build/sysimage.so ]; then
echo "juliaw: rebuilding system image..."
# Generate temporary project folder
rm -rf $HOME/.juliaw
mkdir -p $HOME/.juliaw/src
cp Project.toml Manifest.toml $HOME/.juliaw
NAME=$(julia -e 'using TOML; toml = TOML.parsefile("Project.toml"); "name" in keys(toml) && print(toml["name"])')
if [ ! -z $NAME ]; then
cat > $HOME/.juliaw/src/$NAME.jl << EOF
module $NAME
end
EOF
fi
# Add PackageCompiler dependencies to temporary project
julia --project=$HOME/.juliaw -e 'using Pkg; Pkg.add(["PackageCompiler", "TOML", "Logging"])'
# Generate system image scripts
cat > $HOME/.juliaw/sysimage.jl << EOF
using PackageCompiler
using TOML
using Logging
Logging.disable_logging(Logging.Info)
mkpath("$PWD/build")
println("juliaw: generating precompilation statements...")
run(\`julia --project="$PWD" --trace-compile="$PWD"/build/precompile.jl \$(ARGS)\`)
println("juliaw: finding dependencies...")
project = TOML.parsefile("Project.toml")
manifest = TOML.parsefile("Manifest.toml")
deps = Symbol[]
for dep in keys(project["deps"])
if dep in keys(manifest)
# Up to Julia 1.6
dep_entry = manifest[dep][1]
else
# Julia 1.7+
dep_entry = manifest["deps"][dep][1]
end
if "path" in keys(dep_entry)
println(" - \$(dep) [skip]")
else
println(" - \$(dep)")
push!(deps, Symbol(dep))
end
end
println("juliaw: building system image...")
create_sysimage(
deps,
precompile_statements_file = "$PWD/build/precompile.jl",
sysimage_path = "$PWD/build/sysimage.so",
)
EOF
julia --project=$HOME/.juliaw $HOME/.juliaw/sysimage.jl $*
else
julia --project=. --sysimage build/sysimage.so $*
fi

View File

@@ -5,9 +5,10 @@
module RELOG
include("instance/structs.jl")
include("graph/structs.jl")
include("instance/geodb.jl")
include("graph/dist.jl")
include("graph/build.jl")
include("graph/csv.jl")
include("instance/compress.jl")
@@ -15,10 +16,12 @@ include("instance/parse.jl")
include("instance/validate.jl")
include("model/build.jl")
include("model/getsol.jl")
include("model/resolve.jl")
include("model/solve.jl")
include("reports/plant_emissions.jl")
include("reports/plant_outputs.jl")
include("reports/plants.jl")
include("reports/products.jl")
include("reports/tr_emissions.jl")
include("reports/tr.jl")
include("reports/write.jl")

View File

@@ -1,28 +0,0 @@
.navbar-default {
border-bottom: 0px;
background-color: #fff;
box-shadow: 0px 0px 15px rgba(0, 0, 0, 0.2);
}
a, .navbar-default a {
color: #06a !important;
font-weight: normal;
}
.disabled > a {
color: #999 !important;
}
.navbar-default a:hover,
.navbar-default .active,
.active > a {
background-color: #f0f0f0 !important;
}
.icon-bar {
background-color: #666 !important;
}
.navbar-collapse {
border-color: #fff !important;
}

View File

@@ -1,8 +0,0 @@
MathJax.Hub.Config({
"tex2jax": { inlineMath: [ [ '$', '$' ] ] }
});
MathJax.Hub.Config({
config: ["MMLorHTML.js"],
jax: ["input/TeX", "output/HTML-CSS", "output/NativeMML"],
extensions: ["MathMenu.js", "MathZoom.js"]
});

View File

@@ -2,14 +2,6 @@
# Copyright (C) 2020, UChicago Argonne, LLC. All rights reserved.
# Released under the modified BSD license. See COPYING.md for more details.
using Geodesy
function calculate_distance(source_lat, source_lon, dest_lat, dest_lon)::Float64
x = LLA(source_lat, source_lon, 0.0)
y = LLA(dest_lat, dest_lon, 0.0)
return round(distance(x, y) / 1000.0, digits = 2)
end
function build_graph(instance::Instance)::Graph
arcs = []
next_index = 0
@@ -17,6 +9,8 @@ function build_graph(instance::Instance)::Graph
plant_shipping_nodes = ShippingNode[]
collection_shipping_nodes = ShippingNode[]
name_to_process_node_map = Dict{Tuple{AbstractString,AbstractString},ProcessNode}()
process_nodes_by_input_product =
Dict(product => ProcessNode[] for product in instance.products)
shipping_nodes_by_plant = Dict(plant => [] for plant in instance.plants)
@@ -35,6 +29,8 @@ function build_graph(instance::Instance)::Graph
push!(process_nodes, pn)
push!(process_nodes_by_input_product[plant.input], pn)
name_to_process_node_map[(plant.plant_name, plant.location_name)] = pn
for product in keys(plant.output)
sn = ShippingNode(next_index, plant, product, [], [])
next_index += 1
@@ -46,11 +42,12 @@ function build_graph(instance::Instance)::Graph
# Build arcs from collection centers to plants, and from one plant to another
for source in [collection_shipping_nodes; plant_shipping_nodes]
for dest in process_nodes_by_input_product[source.product]
distance = calculate_distance(
distance = _calculate_distance(
source.location.latitude,
source.location.longitude,
dest.location.latitude,
dest.location.longitude,
instance.distance_metric,
)
values = Dict("distance" => distance)
arc = Arc(source, dest, values)
@@ -73,5 +70,24 @@ function build_graph(instance::Instance)::Graph
end
end
return Graph(process_nodes, plant_shipping_nodes, collection_shipping_nodes, arcs)
return Graph(
process_nodes,
plant_shipping_nodes,
collection_shipping_nodes,
arcs,
name_to_process_node_map,
)
end
function print_graph_stats(instance::Instance, graph::Graph)::Nothing
@info @sprintf(" %12d time periods", instance.time)
@info @sprintf(" %12d process nodes", length(graph.process_nodes))
@info @sprintf(" %12d shipping nodes (plant)", length(graph.plant_shipping_nodes))
@info @sprintf(
" %12d shipping nodes (collection)",
length(graph.collection_shipping_nodes)
)
@info @sprintf(" %12d arcs", length(graph.arcs))
return
end

57
src/graph/dist.jl Normal file
View File

@@ -0,0 +1,57 @@
# RELOG: Reverse Logistics Optimization
# Copyright (C) 2020, UChicago Argonne, LLC. All rights reserved.
# Released under the modified BSD license. See COPYING.md for more details.
using Geodesy
using NearestNeighbors
using DataFrames
function _calculate_distance(
source_lat,
source_lon,
dest_lat,
dest_lon,
::EuclideanDistance,
)::Float64
x = LLA(source_lat, source_lon, 0.0)
y = LLA(dest_lat, dest_lon, 0.0)
return round(euclidean_distance(x, y) / 1000.0, digits = 3)
end
function _calculate_distance(
source_lat,
source_lon,
dest_lat,
dest_lon,
metric::KnnDrivingDistance,
)::Float64
if metric.tree === nothing
basedir = joinpath(dirname(@__FILE__), "..", "..", "data")
csv_filename = joinpath(basedir, "dist_driving.csv")
# Download pre-computed driving data
if !isfile(csv_filename)
_download_zip(
"https://axavier.org/RELOG/0.6/data/dist_driving_0b9a6ad6.zip",
basedir,
csv_filename,
0x0b9a6ad6,
)
end
# Fit kNN model
df = DataFrame(CSV.File(csv_filename))
coords = Matrix(df[!, [:source_lat, :source_lon, :dest_lat, :dest_lon]])'
metric.ratios = Matrix(df[!, [:ratio]])
metric.tree = KDTree(coords)
end
# Compute Euclidean distance
dist_euclidean =
_calculate_distance(source_lat, source_lon, dest_lat, dest_lon, EuclideanDistance())
# Predict ratio
idxs, _ = knn(metric.tree, [source_lat, source_lon, dest_lat, dest_lon], 5)
ratio_pred = mean(metric.ratios[idxs])
return round(dist_euclidean * ratio_pred, digits = 3)
end

View File

@@ -32,4 +32,13 @@ mutable struct Graph
plant_shipping_nodes::Vector{ShippingNode}
collection_shipping_nodes::Vector{ShippingNode}
arcs::Vector{Arc}
name_to_process_node_map::Dict{Tuple{AbstractString,AbstractString},ProcessNode}
end
function Base.show(io::IO, instance::Graph)
print(io, "RELOG graph with ")
print(io, "$(length(instance.process_nodes)) process nodes, ")
print(io, "$(length(instance.plant_shipping_nodes)) plant shipping nodes, ")
print(io, "$(length(instance.collection_shipping_nodes)) collection shipping nodes, ")
print(io, "$(length(instance.arcs)) arcs")
end

212
src/instance/geodb.jl Normal file
View File

@@ -0,0 +1,212 @@
# RELOG: Reverse Logistics Optimization
# Copyright (C) 2020, UChicago Argonne, LLC. All rights reserved.
# Released under the modified BSD license. See COPYING.md for more details.
using CRC
using CSV
using DataFrames
using Shapefile
using Statistics
using ZipFile
using ProgressBars
using OrderedCollections
import Downloads: download
import Base: parse
crc32 = crc(CRC_32)
struct GeoPoint
lat::Float64
lon::Float64
end
struct GeoRegion
centroid::GeoPoint
population::Int
GeoRegion(; centroid, population) = new(centroid, population)
end
DB_CACHE = Dict{String,Dict{String,GeoRegion}}()
function centroid(geom::Shapefile.Polygon)::GeoPoint
x_max, x_min, y_max, y_min = -Inf, Inf, -Inf, Inf
for p in geom.points
x_max = max(x_max, p.x)
x_min = min(x_min, p.x)
y_max = max(y_max, p.y)
y_min = min(y_min, p.y)
end
x_center = (x_max + x_min) / 2.0
y_center = (y_max + y_min) / 2.0
return GeoPoint(round(y_center, digits = 5), round(x_center, digits = 5))
end
function _download_file(url, output, expected_crc32)::Nothing
if isfile(output)
return
end
mkpath(dirname(output))
@info "Downloading: $url"
fname = download(url)
actual_crc32 = open(crc32, fname)
expected_crc32 == actual_crc32 || error("CRC32 mismatch")
cp(fname, output)
return
end
function _download_zip(url, outputdir, expected_output_file, expected_crc32)::Nothing
if isfile(expected_output_file)
return
end
mkpath(outputdir)
@info "Downloading: $url"
zip_filename = download(url)
actual_crc32 = open(crc32, zip_filename)
expected_crc32 == actual_crc32 || error("CRC32 mismatch")
open(zip_filename) do zip_file
zr = ZipFile.Reader(zip_file)
for file in zr.files
open(joinpath(outputdir, file.name), "w") do output_file
write(output_file, read(file))
end
end
end
return
end
function _geodb_load_gov_census(;
db_name,
extract_cols,
shp_crc32,
shp_filename,
shp_url,
population_url,
population_crc32,
population_col,
population_preprocess,
population_join,
)::Dict{String,GeoRegion}
basedir = joinpath(dirname(@__FILE__), "..", "..", "data", db_name)
csv_filename = "$basedir/locations.csv"
if !isfile(csv_filename)
# Download required files
_download_zip(shp_url, basedir, joinpath(basedir, shp_filename), shp_crc32)
_download_file(population_url, "$basedir/population.csv", population_crc32)
# Read shapefile
@info "Processing: $shp_filename"
table = Shapefile.Table(joinpath(basedir, shp_filename))
geoms = Shapefile.shapes(table)
# Build empty dataframe
df = DataFrame()
cols = extract_cols(table, 1)
for k in keys(cols)
df[!, k] = []
end
df[!, "latitude"] = Float64[]
df[!, "longitude"] = Float64[]
# Add regions to dataframe
for (i, geom) in tqdm(enumerate(geoms))
c = centroid(geom)
cols = extract_cols(table, i)
push!(df, [values(cols)..., c.lat, c.lon])
end
sort!(df)
# Join with population data
population = DataFrame(CSV.File("$basedir/population.csv"))
population_preprocess(population)
population = population[:, [population_join, population_col]]
rename!(population, population_col => "population")
df = leftjoin(df, population, on = population_join)
# Write output
CSV.write(csv_filename, df)
end
if db_name keys(DB_CACHE)
csv = CSV.File(csv_filename)
DB_CACHE[db_name] = Dict(
string(row.id) => GeoRegion(
centroid = GeoPoint(row.latitude, row.longitude),
population = (row.population === missing ? 0 : row.population),
) for row in csv
)
end
return DB_CACHE[db_name]
end
# 2018 US counties
# -----------------------------------------------------------------------------
function _extract_cols_2018_us_county(
table::Shapefile.Table,
i::Int,
)::OrderedDict{String,Any}
return OrderedDict(
"id" => table.STATEFP[i] * table.COUNTYFP[i],
"statefp" => table.STATEFP[i],
"countyfp" => table.COUNTYFP[i],
"name" => table.NAME[i],
)
end
function _population_preprocess_2018_us_county(df)
df[!, "id"] = [@sprintf("%02d%03d", row.STATE, row.COUNTY) for row in eachrow(df)]
end
function _geodb_load_2018_us_county()::Dict{String,GeoRegion}
return _geodb_load_gov_census(
db_name = "2018-us-county",
extract_cols = _extract_cols_2018_us_county,
shp_crc32 = 0x83eaec6d,
shp_filename = "cb_2018_us_county_500k.shp",
shp_url = "https://www2.census.gov/geo/tiger/GENZ2018/shp/cb_2018_us_county_500k.zip",
population_url = "https://www2.census.gov/programs-surveys/popest/datasets/2010-2019/counties/totals/co-est2019-alldata.csv",
population_crc32 = 0xf85b0405,
population_col = "POPESTIMATE2019",
population_join = "id",
population_preprocess = _population_preprocess_2018_us_county,
)
end
# US States
# -----------------------------------------------------------------------------
function _extract_cols_us_state(table::Shapefile.Table, i::Int)::OrderedDict{String,Any}
return OrderedDict(
"id" => table.STUSPS[i],
"statefp" => parse(Int, table.STATEFP[i]),
"name" => table.NAME[i],
)
end
function _population_preprocess_us_state(df)
rename!(df, "STATE" => "statefp")
end
function _geodb_load_us_state()::Dict{String,GeoRegion}
return _geodb_load_gov_census(
db_name = "us-state",
extract_cols = _extract_cols_us_state,
shp_crc32 = 0x9469e5ca,
shp_filename = "cb_2018_us_state_500k.shp",
shp_url = "https://www2.census.gov/geo/tiger/GENZ2018/shp/cb_2018_us_state_500k.zip",
population_url = "http://www2.census.gov/programs-surveys/popest/datasets/2010-2019/national/totals/nst-est2019-alldata.csv",
population_crc32 = 0x191cc64c,
population_col = "POPESTIMATE2019",
population_join = "statefp",
population_preprocess = _population_preprocess_us_state,
)
end
function geodb_load(db_name::AbstractString)::Dict{String,GeoRegion}
db_name == "2018-us-county" && return _geodb_load_2018_us_county()
db_name == "us-state" && return _geodb_load_us_state()
error("Unknown database: $db_name")
end
function geodb_query(name)::GeoRegion
db_name, id = split(name, ":")
return geodb_load(db_name)[id]
end

View File

@@ -23,10 +23,23 @@ function parse(json)::Instance
validate(json, Schema(json_schema))
building_period = [1]
if "building period (years)" in keys(json)
building_period = json["building period (years)"]
if "building period (years)" in keys(json["parameters"])
building_period = json["parameters"]["building period (years)"]
end
distance_metric = EuclideanDistance()
if "distance metric" in keys(json["parameters"])
metric_name = json["parameters"]["distance metric"]
if metric_name == "driving"
distance_metric = KnnDrivingDistance()
elseif metric_name == "Euclidean"
# nop
else
error("Unknown distance metric: $metric_name")
end
end
@show distance_metric
plants = Plant[]
products = Product[]
collection_centers = CollectionCenter[]
@@ -53,6 +66,11 @@ function parse(json)::Instance
# Create collection centers
if "initial amounts" in keys(product_dict)
for (center_name, center_dict) in product_dict["initial amounts"]
if "location" in keys(center_dict)
region = geodb_query(center_dict["location"])
center_dict["latitude (deg)"] = region.centroid.lat
center_dict["longitude (deg)"] = region.centroid.lon
end
center = CollectionCenter(
length(collection_centers) + 1,
center_name,
@@ -95,6 +113,13 @@ function parse(json)::Instance
disposal_limit = Dict(p => [0.0 for t = 1:T] for p in keys(output))
disposal_cost = Dict(p => [0.0 for t = 1:T] for p in keys(output))
# GeoDB
if "location" in keys(location_dict)
region = geodb_query(location_dict["location"])
location_dict["latitude (deg)"] = region.centroid.lat
location_dict["longitude (deg)"] = region.centroid.lon
end
# Disposal
if "disposal" in keys(location_dict)
for (product_name, disposal_dict) in location_dict["disposal"]
@@ -164,5 +189,12 @@ function parse(json)::Instance
@info @sprintf("%12d collection centers", length(collection_centers))
@info @sprintf("%12d candidate plant locations", length(plants))
return Instance(T, products, collection_centers, plants, building_period)
return Instance(
T,
products,
collection_centers,
plants,
building_period,
distance_metric,
)
end

View File

@@ -48,10 +48,21 @@ mutable struct Plant
storage_cost::Vector{Float64}
end
abstract type DistanceMetric end
Base.@kwdef mutable struct KnnDrivingDistance <: DistanceMetric
tree = nothing
ratios = nothing
end
mutable struct EuclideanDistance <: DistanceMetric end
mutable struct Instance
time::Int64
products::Vector{Product}
collection_centers::Vector{CollectionCenter}
plants::Vector{Plant}
building_period::Vector{Int64}
distance_metric::DistanceMetric
end

View File

@@ -12,14 +12,10 @@ function validate(json, schema)
result = JSONSchema.validate(json, schema)
if result !== nothing
if result isa JSONSchema.SingleIssue
path = join(result.path, "")
if length(path) == 0
path = "root"
end
msg = "$(result.msg) in $(path)"
msg = "$(result.reason) in $(result.path)"
else
msg = convert(String, result)
end
throw(msg)
throw("Error parsing input file: $(msg)")
end
end

View File

@@ -4,7 +4,6 @@
using JuMP, LinearAlgebra, Geodesy, Cbc, Clp, ProgressBars, Printf, DataStructures
function build_model(instance::Instance, graph::Graph, optimizer)::JuMP.Model
model = Model(optimizer)
model[:instance] = instance

View File

@@ -45,6 +45,9 @@ function get_solution(model::JuMP.Model; marginal_costs = true)
"Marginal cost (\$/tonne)" => [
round(abs(JuMP.shadow_price(model[:eq_balance][n, t])), digits = 2) for t = 1:T
],
"Latitude (deg)" => n.location.latitude,
"Longitude (deg)" => n.location.longitude,
"Amount (tonne)" => n.location.amount,
)
if n.product.name keys(output["Products"])
output["Products"][n.product.name] = OrderedDict()

97
src/model/resolve.jl Normal file
View File

@@ -0,0 +1,97 @@
# RELOG: Reverse Logistics Optimization
# Copyright (C) 2020-2021, UChicago Argonne, LLC. All rights reserved.
# Released under the modified BSD license. See COPYING.md for more details.
using JuMP
function resolve(model_old, filename::AbstractString; kwargs...)::OrderedDict
@info "Reading $filename..."
instance = RELOG.parsefile(filename)
return resolve(model_old, instance; kwargs...)
end
function resolve(model_old, instance::Instance; optimizer = nothing)::OrderedDict
milp_optimizer = lp_optimizer = optimizer
if optimizer === nothing
milp_optimizer = _get_default_milp_optimizer()
lp_optimizer = _get_default_lp_optimizer()
end
@info "Building new graph..."
graph = build_graph(instance)
_print_graph_stats(instance, graph)
@info "Building new optimization model..."
model_new = RELOG.build_model(instance, graph, milp_optimizer)
@info "Fixing decision variables..."
_fix_plants!(model_old, model_new)
JuMP.set_optimizer(model_new, lp_optimizer)
@info "Optimizing MILP..."
JuMP.optimize!(model_new)
if !has_values(model_new)
@warn("No solution available")
return OrderedDict()
end
@info "Extracting solution..."
solution = get_solution(model_new, marginal_costs = true)
return solution
end
function _fix_plants!(model_old, model_new)::Nothing
T = model_new[:instance].time
# Fix open_plant variables
for ((node_old, t), var_old) in model_old[:open_plant]
value_old = JuMP.value(var_old)
node_new = model_new[:graph].name_to_process_node_map[(
node_old.location.plant_name,
node_old.location.location_name,
)]
var_new = model_new[:open_plant][node_new, t]
JuMP.unset_binary(var_new)
JuMP.fix(var_new, value_old)
end
# Fix is_open variables
for ((node_old, t), var_old) in model_old[:is_open]
value_old = JuMP.value(var_old)
node_new = model_new[:graph].name_to_process_node_map[(
node_old.location.plant_name,
node_old.location.location_name,
)]
var_new = model_new[:is_open][node_new, t]
JuMP.unset_binary(var_new)
JuMP.fix(var_new, value_old)
end
# Fix plant capacities
for ((node_old, t), var_old) in model_old[:capacity]
value_old = JuMP.value(var_old)
node_new = model_new[:graph].name_to_process_node_map[(
node_old.location.plant_name,
node_old.location.location_name,
)]
var_new = model_new[:capacity][node_new, t]
JuMP.delete_lower_bound(var_new)
JuMP.delete_upper_bound(var_new)
JuMP.fix(var_new, value_old)
end
# Fix plant expansion
for ((node_old, t), var_old) in model_old[:expansion]
value_old = JuMP.value(var_old)
node_new = model_new[:graph].name_to_process_node_map[(
node_old.location.plant_name,
node_old.location.location_name,
)]
var_new = model_new[:expansion][node_new, t]
JuMP.delete_lower_bound(var_new)
JuMP.delete_upper_bound(var_new)
JuMP.fix(var_new, value_old)
end
end

View File

@@ -4,24 +4,16 @@
using JuMP, LinearAlgebra, Geodesy, Cbc, Clp, ProgressBars, Printf, DataStructures
default_milp_optimizer = optimizer_with_attributes(Cbc.Optimizer, "logLevel" => 0)
default_lp_optimizer = optimizer_with_attributes(Clp.Optimizer, "LogLevel" => 0)
function _get_default_milp_optimizer()
return optimizer_with_attributes(Cbc.Optimizer, "logLevel" => 0)
end
function solve(
instance::Instance;
optimizer = nothing,
output = nothing,
marginal_costs = true,
)
function _get_default_lp_optimizer()
return optimizer_with_attributes(Clp.Optimizer, "LogLevel" => 0)
end
milp_optimizer = lp_optimizer = optimizer
if optimizer == nothing
milp_optimizer = default_milp_optimizer
lp_optimizer = default_lp_optimizer
end
@info "Building graph..."
graph = RELOG.build_graph(instance)
function _print_graph_stats(instance::Instance, graph::Graph)::Nothing
@info @sprintf(" %12d time periods", instance.time)
@info @sprintf(" %12d process nodes", length(graph.process_nodes))
@info @sprintf(" %12d shipping nodes (plant)", length(graph.plant_shipping_nodes))
@@ -30,6 +22,26 @@ function solve(
length(graph.collection_shipping_nodes)
)
@info @sprintf(" %12d arcs", length(graph.arcs))
return
end
function solve(
instance::Instance;
optimizer = nothing,
output = nothing,
marginal_costs = true,
return_model = false,
)
milp_optimizer = lp_optimizer = optimizer
if optimizer == nothing
milp_optimizer = _get_default_milp_optimizer()
lp_optimizer = _get_default_lp_optimizer()
end
@info "Building graph..."
graph = RELOG.build_graph(instance)
_print_graph_stats(instance, graph)
@info "Building optimization model..."
model = RELOG.build_model(instance, graph, milp_optimizer)
@@ -38,8 +50,7 @@ function solve(
JuMP.optimize!(model)
if !has_values(model)
@warn "No solution available"
return OrderedDict()
error("No solution available")
end
if marginal_costs
@@ -63,7 +74,11 @@ function solve(
write(solution, output)
end
return solution
if return_model
return solution, model
else
return solution
end
end
function solve(filename::AbstractString; heuristic = false, kwargs...)

43
src/reports/products.jl Normal file
View File

@@ -0,0 +1,43 @@
# RELOG: Reverse Logistics Optimization
# Copyright (C) 2020, UChicago Argonne, LLC. All rights reserved.
# Released under the modified BSD license. See COPYING.md for more details.
using DataFrames
using CSV
function products_report(solution; marginal_costs = true)::DataFrame
df = DataFrame()
df."product name" = String[]
df."location name" = String[]
df."latitude (deg)" = Float64[]
df."longitude (deg)" = Float64[]
df."year" = Int[]
df."amount (tonne)" = Float64[]
df."marginal cost (\$/tonne)" = Float64[]
T = length(solution["Energy"]["Plants (GJ)"])
for (prod_name, prod_dict) in solution["Products"]
for (location_name, location_dict) in prod_dict
for year = 1:T
marginal_cost = location_dict["Marginal cost (\$/tonne)"][year]
latitude = round(location_dict["Latitude (deg)"], digits = 6)
longitude = round(location_dict["Longitude (deg)"], digits = 6)
amount = location_dict["Amount (tonne)"][year]
push!(
df,
[
prod_name,
location_name,
latitude,
longitude,
year,
amount,
marginal_cost,
],
)
end
end
end
return df
end
write_products_report(solution, filename) = CSV.write(filename, products_report(solution))

View File

@@ -4,6 +4,7 @@
using DataFrames
using CSV
import Base: write
function write(solution::AbstractDict, filename::AbstractString)
@info "Writing solution: $filename"

View File

@@ -12,7 +12,12 @@
"Parameters": {
"type": "object",
"properties": {
"time horizon (years)": { "type": "number" }
"time horizon (years)": {
"type": "number"
},
"distance metric": {
"type": "string"
}
},
"required": [
"time horizon (years)"
@@ -23,17 +28,27 @@
"additionalProperties": {
"type": "object",
"properties": {
"input": { "type": "string" },
"input": {
"type": "string"
},
"outputs (tonne/tonne)": {
"type": "object",
"additionalProperties": { "type": "number" }
"additionalProperties": {
"type": "number"
}
},
"energy (GJ/tonne)": {
"$ref": "#/definitions/TimeSeries"
},
"energy (GJ/tonne)": { "$ref": "#/definitions/TimeSeries" },
"emissions (tonne/tonne)": {
"type": "object",
"additionalProperties": { "$ref": "#/definitions/TimeSeries" }
"additionalProperties": {
"$ref": "#/definitions/TimeSeries"
}
},
"locations": { "$ref": "#/definitions/PlantLocation" }
"locations": {
"$ref": "#/definitions/PlantLocation"
}
},
"required": [
"input",
@@ -46,15 +61,26 @@
"additionalProperties": {
"type": "object",
"properties": {
"latitude (deg)": { "type": "number" },
"longitude (deg)": { "type": "number" },
"location": {
"type": "string"
},
"latitude (deg)": {
"type": "number"
},
"longitude (deg)": {
"type": "number"
},
"disposal": {
"type": "object",
"additionalProperties": {
"type": "object",
"properties": {
"cost ($/tonne)": { "$ref": "#/definitions/TimeSeries" },
"limit (tonne)": { "$ref": "#/definitions/TimeSeries" }
"cost ($/tonne)": {
"$ref": "#/definitions/TimeSeries"
},
"limit (tonne)": {
"$ref": "#/definitions/TimeSeries"
}
},
"required": [
"cost ($/tonne)"
@@ -64,22 +90,32 @@
"storage": {
"type": "object",
"properties": {
"cost ($/tonne)": { "$ref": "#/definitions/TimeSeries" },
"limit (tonne)": { "type": "number" }
"cost ($/tonne)": {
"$ref": "#/definitions/TimeSeries"
},
"limit (tonne)": {
"type": "number"
}
},
"required": [
"cost ($/tonne)",
"limit (tonne)"
]
},
},
"capacities (tonne)": {
"type": "object",
"additionalProperties": {
"type": "object",
"properties": {
"variable operating cost ($/tonne)": { "$ref": "#/definitions/TimeSeries" },
"fixed operating cost ($)": { "$ref": "#/definitions/TimeSeries" },
"opening cost ($)": { "$ref": "#/definitions/TimeSeries" }
"variable operating cost ($/tonne)": {
"$ref": "#/definitions/TimeSeries"
},
"fixed operating cost ($)": {
"$ref": "#/definitions/TimeSeries"
},
"opening cost ($)": {
"$ref": "#/definitions/TimeSeries"
}
},
"required": [
"variable operating cost ($/tonne)",
@@ -87,11 +123,9 @@
"opening cost ($)"
]
}
}
}
},
"required": [
"latitude (deg)",
"longitude (deg)",
"capacities (tonne)"
]
}
@@ -101,13 +135,20 @@
"additionalProperties": {
"type": "object",
"properties": {
"latitude (deg)": { "type": "number" },
"longitude (deg)": { "type": "number" },
"amount (tonne)": { "$ref": "#/definitions/TimeSeries" }
"location": {
"type": "string"
},
"latitude (deg)": {
"type": "number"
},
"longitude (deg)": {
"type": "number"
},
"amount (tonne)": {
"$ref": "#/definitions/TimeSeries"
}
},
"required": [
"latitude (deg)",
"longitude (deg)",
"amount (tonne)"
]
}
@@ -117,25 +158,39 @@
"additionalProperties": {
"type": "object",
"properties": {
"transportation cost ($/km/tonne)": { "$ref": "#/definitions/TimeSeries" },
"transportation energy (J/km/tonne)": { "$ref": "#/definitions/TimeSeries" },
"transportation cost ($/km/tonne)": {
"$ref": "#/definitions/TimeSeries"
},
"transportation energy (J/km/tonne)": {
"$ref": "#/definitions/TimeSeries"
},
"transportation emissions (tonne/km/tonne)": {
"type": "object",
"additionalProperties": { "$ref": "#/definitions/TimeSeries" }
"additionalProperties": {
"$ref": "#/definitions/TimeSeries"
}
},
"initial amounts": { "$ref": "#/definitions/InitialAmount" }
"initial amounts": {
"$ref": "#/definitions/InitialAmount"
}
},
"required": [
"transportation cost ($/km/tonne)"
]
}
}
}
},
"type": "object",
"properties": {
"parameters": { "$ref": "#/definitions/Parameters" },
"plants": { "$ref": "#/definitions/Plant" },
"products": { "$ref": "#/definitions/Product" }
"parameters": {
"$ref": "#/definitions/Parameters"
},
"plants": {
"$ref": "#/definitions/Plant"
},
"products": {
"$ref": "#/definitions/Product"
}
},
"required": [
"parameters",

View File

@@ -21,7 +21,7 @@ using RELOG
@test node.outgoing_arcs[1].source.location.name == "C1"
@test node.outgoing_arcs[1].dest.location.plant_name == "F1"
@test node.outgoing_arcs[1].dest.location.location_name == "L1"
@test node.outgoing_arcs[1].values["distance"] == 1095.62
@test node.outgoing_arcs[1].values["distance"] == 1695.364
node = process_node_by_location_name["L1"]
@test node.location.plant_name == "F1"

25
test/graph/dist_test.jl Normal file
View File

@@ -0,0 +1,25 @@
# RELOG: Reverse Logistics Optimization
# Copyright (C) 2020, UChicago Argonne, LLC. All rights reserved.
# Released under the modified BSD license. See COPYING.md for more details.
using RELOG
@testset "KnnDrivingDistance" begin
# Euclidean distance between Chicago and Indianapolis
@test RELOG._calculate_distance(
41.866,
-87.656,
39.764,
-86.148,
RELOG.EuclideanDistance(),
) == 265.818
# Approximate driving distance between Chicago and Indianapolis
@test RELOG._calculate_distance(
41.866,
-87.656,
39.764,
-86.148,
RELOG.KnnDrivingDistance(),
) == 316.43
end

View File

@@ -0,0 +1,25 @@
# RELOG: Reverse Logistics Optimization
# Copyright (C) 2020, UChicago Argonne, LLC. All rights reserved.
# Released under the modified BSD license. See COPYING.md for more details.
using RELOG
@testset "geodb_query (2018-us-county)" begin
region = RELOG.geodb_query("2018-us-county:17043")
@test region.centroid.lat == 41.83956
@test region.centroid.lon == -88.08857
@test region.population == 922_921
end
# @testset "geodb_query (2018-us-zcta)" begin
# region = RELOG.geodb_query("2018-us-zcta:60439")
# @test region.centroid.lat == 41.68241
# @test region.centroid.lon == -87.98954
# end
@testset "geodb_query (us-state)" begin
region = RELOG.geodb_query("us-state:IL")
@test region.centroid.lat == 39.73939
@test region.centroid.lon == -89.50414
@test region.population == 12_671_821
end

View File

@@ -70,7 +70,17 @@ using RELOG
@test plant.disposal_limit[p4] == [0, 0]
end
@testset "parse (invalid)" begin
@testset "parse (geodb)" begin
basedir = dirname(@__FILE__)
@test_throws String RELOG.parsefile("$basedir/../fixtures/s1-wrong-length.json")
instance = RELOG.parsefile("$basedir/../../instances/s2.json")
centers = instance.collection_centers
@test centers[1].name == "C1"
@test centers[1].latitude == 41.83956
@test centers[1].longitude == -88.08857
end
# @testset "parse (invalid)" begin
# basedir = dirname(@__FILE__)
# @test_throws ErrorException RELOG.parsefile("$basedir/../fixtures/s1-wrong-length.json")
# end

View File

@@ -0,0 +1,11 @@
# Copyright (C) 2020 Argonne National Laboratory
# Written by Alinson Santos Xavier <axavier@anl.gov>
using RELOG
@testset "Resolve" begin
# Shoud not crash
filename = "$(pwd())/../instances/s1.json"
solution_old, model_old = RELOG.solve(filename, return_model = true)
solution_new = RELOG.resolve(model_old, filename)
end

View File

@@ -38,7 +38,7 @@ end
for (location_name, location_dict) in json["products"]["P1"]["initial amounts"]
location_dict["amount (tonne)"] *= 1000
end
RELOG.solve(RELOG.parse(json))
@test_throws ErrorException("No solution available") RELOG.solve(RELOG.parse(json))
end
@testset "solve (with storage)" begin

View File

@@ -9,10 +9,11 @@ using RELOG, JSON, GZip
solution = RELOG.solve("$(pwd())/../instances/s1.json")
tmp_filename = tempname()
# The following should not crash
RELOG.write_plants_report(solution, tmp_filename)
RELOG.write_plant_outputs_report(solution, tmp_filename)
RELOG.write_plant_emissions_report(solution, tmp_filename)
RELOG.write_transportation_report(solution, tmp_filename)
RELOG.write_plant_outputs_report(solution, tmp_filename)
RELOG.write_plants_report(solution, tmp_filename)
RELOG.write_products_report(solution, tmp_filename)
RELOG.write_transportation_emissions_report(solution, tmp_filename)
RELOG.write_transportation_report(solution, tmp_filename)
end
end

View File

@@ -6,14 +6,17 @@ using Test
@testset "RELOG" begin
@testset "Instance" begin
include("instance/compress_test.jl")
include("instance/geodb_test.jl")
include("instance/parse_test.jl")
end
@testset "Graph" begin
include("graph/build_test.jl")
include("graph/dist_test.jl")
end
@testset "Model" begin
include("model/build_test.jl")
include("model/solve_test.jl")
include("model/resolve_test.jl")
end
include("reports_test.jl")
end