├── .gitignore ├── LICENSE ├── README.md ├── data └── eddy.zip ├── plots └── .gitkeep └── pydca.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.swp 2 | *.png 3 | data/* 4 | .mypy_cache/** 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pydca 2 | 3 | A simple example of implementing Arps decline curve analysis in Python, as described [on my blog](https://usethe.computer/posts/15-minimalist-dca-in-python.html). Example data is courtesy of the [New Mexico Oil Conservation Division](http://www.emnrd.state.nm.us/OCD/). 4 | 5 | Freely available under the Apache License, version 2.0. 6 | 7 | ### (c) 2020 [dwt](https://usethe.computer) | [terminus data science, LLC](https://terminusdata.science) 8 | -------------------------------------------------------------------------------- /data/eddy.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/derrickturk/pydca/5237f101b27f5eca20107012f578e8cd7bc0f3fa/data/eddy.zip -------------------------------------------------------------------------------- /plots/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/derrickturk/pydca/5237f101b27f5eca20107012f578e8cd7bc0f3fa/plots/.gitkeep -------------------------------------------------------------------------------- /pydca.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 terminus data science, LLC 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import sys 16 | import csv 17 | import calendar 18 | from datetime import date, timedelta 19 | 20 | import numpy as np 21 | import matplotlib.pyplot as plt # type: ignore 22 | from scipy.optimize import minimize # type: ignore 23 | 24 | import dataclasses as dc 25 | 26 | from typing import Iterable, Iterator, List, Optional, TextIO, Tuple 27 | 28 | YEAR_DAYS: float = 365.25 # days 29 | DOWNTIME_CUTOFF = 1.0 # daily rate 30 | 31 | MIN_PTS_FIT: int = 3 # minimum # of points for fitting 32 | PEAK_SHIFT_MAX: int = 6 # maximum # of months to peak for fitting 33 | 34 | _GUESS_DI_NOM: float = 1.0 # nominal annual decline 35 | _GUESS_B = 1.5 36 | 37 | _FIT_BOUNDS: List[Tuple[Optional[float], Optional[float]]] = [ 38 | (0.0, None), # initial rate 39 | (0.0, None), # nominal annual decline 40 | (0.0, 2.0), # b 41 | ] 42 | 43 | @dc.dataclass(frozen=True) 44 | class ArpsDecline: 45 | qi: float # daily rate 46 | Di_nom: float # nominal annual decline 47 | b: float # unitless exponent 48 | 49 | def __post_init__(self): 50 | if self.qi < 0.0: 51 | raise ValueError('Negative qi') 52 | if self.Di_nom < 0.0: 53 | raise ValueError('Negative Di_nom') 54 | if self.b < 0.0 or self.b > 2.0: 55 | raise ValueError(f'Invalid b: {self.b}') 56 | 57 | # time (years) 58 | # returns (daily rate) 59 | def rate(self, time: np.ndarray) -> np.ndarray: 60 | if self.b == 0: 61 | return self.qi * np.exp(-self.Di_nom * time) 62 | elif self.b == 1.0: 63 | return self.qi / (1.0 + self.Di_nom * time) 64 | else: 65 | return ( 66 | self.qi / (1.0 + self.b * self.Di_nom * time) ** (1.0 / self.b) 67 | ) 68 | 69 | @staticmethod 70 | def clamped(qi: float, Di_nom: float, b: float) -> 'ArpsDecline': 71 | return ArpsDecline( 72 | max(qi, 0.0), 73 | max(Di_nom, 0.0), 74 | max(min(b, 2.0), 0.0), 75 | ) 76 | 77 | @dc.dataclass(frozen=True) 78 | class DailyOil: 79 | api: str 80 | days_on: np.ndarray # time (days) 81 | oil: np.ndarray # daily rate 82 | prior_cum: Optional[float] # prior cumulative as of 1993/01 if available 83 | 84 | def __post_init__(self): 85 | if len(self.days_on) != len(self.oil): 86 | raise ValueError('Different lengths for days on and oil rate') 87 | 88 | def best_fit(self) -> ArpsDecline: 89 | initial_guess = np.array([ 90 | np.max(self.oil), # guess qi = peak rate 91 | _GUESS_DI_NOM, 92 | _GUESS_B, 93 | ]) 94 | 95 | fit = minimize( 96 | lambda params: self._sse(ArpsDecline.clamped(*params)), 97 | initial_guess, method='L-BFGS-B', bounds=_FIT_BOUNDS) 98 | return ArpsDecline.clamped(*fit.x) 99 | 100 | # filter this data set to only peak-forward production 101 | def peak_forward(self) -> Tuple[int, 'DailyOil']: 102 | if len(self.oil) == 0: 103 | return 0, self 104 | peak_idx = np.argmax(self.oil) 105 | return peak_idx, DailyOil(self.api, 106 | self.days_on[peak_idx:], self.oil[peak_idx:], self.prior_cum) 107 | 108 | # filter this data set to drop "downtime" (zero-production days) 109 | def no_downtime(self, cutoff: float = DOWNTIME_CUTOFF) -> 'DailyOil': 110 | keep_idx = self.oil > cutoff 111 | return DailyOil(self.api, self.days_on[keep_idx], self.oil[keep_idx], 112 | self.prior_cum) 113 | 114 | # sum of squared error for a given fit to this data 115 | def _sse(self, fit: ArpsDecline) -> float: 116 | time_years = self.days_on / YEAR_DAYS 117 | forecast = fit.rate(time_years) 118 | return np.sum((forecast - self.oil) ** 2) 119 | 120 | @dc.dataclass(frozen=True) 121 | class MonthlyRecord: 122 | api: str 123 | year: int 124 | month: int 125 | oil: Optional[float] 126 | gas: Optional[float] 127 | water: Optional[float] 128 | 129 | def month_days(year: int, month: int) -> int: 130 | return calendar.monthrange(year, month)[1] 131 | 132 | def mid_month(year: int, month: int) -> date: 133 | return date(year, month, 1) + timedelta(days=month_days(year, month) / 2) 134 | 135 | # precondition: monthly is sorted by API then date 136 | def from_monthly(monthly: Iterable[MonthlyRecord]) -> Iterator[DailyOil]: 137 | last_api: Optional[str] = None 138 | first_prod: Optional[date] = None 139 | prior_cum: Optional[float] = None 140 | days_on: List[float] = list() 141 | oil: List[float] = list() 142 | 143 | for m in monthly: 144 | if m.api != last_api: 145 | if last_api is not None: 146 | yield DailyOil(last_api, np.array(days_on), np.array(oil), 147 | prior_cum) 148 | days_on = list() 149 | oil = list() 150 | last_api = m.api 151 | first_prod = None 152 | 153 | # NM OCD reports cumulative prior to 1993-01-01 as 1992/12 monthly 154 | if m.year == 1992 and m.month == 12: 155 | prior_cum = m.oil 156 | continue 157 | 158 | if first_prod is None: 159 | first_prod = date(m.year, m.month, 1) 160 | 161 | if m.oil is not None: # skip months with missing oil data 162 | days_on.append((mid_month(m.year, m.month) - first_prod).days) 163 | oil.append(m.oil / month_days(m.year, m.month)) 164 | 165 | if last_api is not None: 166 | yield DailyOil(last_api, np.array(days_on), np.array(oil), prior_cum) 167 | 168 | def float_or_none(val: str) -> Optional[float]: 169 | if val == '': 170 | return None 171 | return float(val) 172 | 173 | def read_production_file(prod_file: TextIO, header: bool = True, **csvkw 174 | ) -> Iterator[MonthlyRecord]: 175 | reader = csv.reader(prod_file, **csvkw) 176 | if header: 177 | next(reader) # skip header row 178 | 179 | for (api, yr, mo, o, g, w) in reader: 180 | yield MonthlyRecord(api, int(yr), int(mo), 181 | float_or_none(o), float_or_none(g), float_or_none(w)) 182 | 183 | def main(argv: List[str]) -> int: 184 | if len(argv) != 2: 185 | print(f'Usage: {argv[0]} production-file', file=sys.stderr) 186 | return 1 187 | 188 | with open(argv[1], 'r', newline='') as production_file: 189 | data = read_production_file(production_file, delimiter='\t') 190 | for well in from_monthly(data): 191 | if well.prior_cum is not None: 192 | print(f'{well.api}: production prior to 1993', 193 | file=sys.stderr) 194 | continue 195 | 196 | shift, filtered = well.peak_forward() 197 | if shift > PEAK_SHIFT_MAX: 198 | print(f'{well.api}: peak occurs too late for fitting', 199 | file=sys.stderr) 200 | continue 201 | 202 | filtered = filtered.no_downtime() 203 | if len(filtered.days_on) < MIN_PTS_FIT: 204 | print(f'{well.api}: not enough data', file=sys.stderr) 205 | continue 206 | 207 | plt.semilogy(filtered.days_on, filtered.oil) 208 | best_fit = filtered.best_fit() 209 | plt.semilogy(well.days_on, best_fit.rate(well.days_on / YEAR_DAYS)) 210 | plt.savefig(f'plots/{well.api}.png') 211 | plt.close() 212 | 213 | return 0 214 | 215 | if __name__ == '__main__': 216 | sys.exit(main(sys.argv)) 217 | --------------------------------------------------------------------------------