├── .gitignore ├── LICENSE ├── README.md ├── Tissot_indicatrix_world_map_equirectangular_proj_by_Eric_Gaba_from_wikimedia.png ├── example-hijri.py ├── example-qibla.py ├── example-salat.py ├── generate_extreme.py ├── generate_extreme_egypt.png ├── generate_extreme_isna.png ├── generate_extreme_karachi.png ├── generate_extreme_muhammadiyah.png ├── generate_extreme_mwl.png └── iclib ├── __init__.py ├── formula.py ├── hijri ├── __init__.py └── ummqura.py ├── qibla.py ├── salat.py └── util.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | *.egg-info/ 23 | .installed.cfg 24 | *.egg 25 | 26 | # PyInstaller 27 | # Usually these files are written by a python script from a template 28 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 29 | *.manifest 30 | *.spec 31 | 32 | # Installer logs 33 | pip-log.txt 34 | pip-delete-this-directory.txt 35 | 36 | # Unit test / coverage reports 37 | htmlcov/ 38 | .tox/ 39 | .coverage 40 | .coverage.* 41 | .cache 42 | nosetests.xml 43 | coverage.xml 44 | *,cover 45 | 46 | # Translations 47 | *.mo 48 | *.pot 49 | 50 | # Django stuff: 51 | *.log 52 | 53 | # Sphinx documentation 54 | docs/_build/ 55 | 56 | # PyBuilder 57 | target/ 58 | -------------------------------------------------------------------------------- /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 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ICLib Python 2 | Islamic Calculation Library (ICLib) contains calculations/algorithms needed specifically by muslims and people in muslim countries, such as salat (prayer) times, qibla direction, and Hijri conversion. 3 | 4 | ## Introduction 5 | 6 | This library is inspired by [Islamic Tools Library (ITL)](http://projects.arabeyes.org/project.php?proj=ITL) which seems no longer be maintained. ITL is LGPL-licensed, so you cannot use it for closed source applications if you cannot provide an easy way for the users (of the application, not the developer who uses the library) to change and modify the library used in your application. ICLib is written from "zero" and aims to be more flexible by providing more programming languages and using Apache license, so you can use it even for closed source commercial applications _as long as_ it is for good deeds. I don't know if we need to use modified Apache license to state that limitation :). 7 | 8 | Calculation of **prayer times** and **qibla direction** is based on **Dr. Eng. Rinto Anugraha, M.Si.** from Universitas Gadjah Mada, Indonesia (published in 2012 AD), and also refer to **Pedoman Hisab Muhammadiyah** (published in 1430 AH / 2009 AD), **Wikipedia** (English version), etc for comparison and complement. **Umm al-Qura Hijri calendar** month lengths table is based on the output of ITL (not the source code). 9 | 10 | This library is written in Python, see also the [Java](https://github.com/fikr4n/iclib-java) version. We plan to make the C version, and probably other languages. We also plan to implement hilal (crescent) altitude calculation for new moon estimation (not as reference for ibadah). 11 | 12 | **Notes on Hijri conversion** 13 | 14 | Any Hijri conversion including Umm al-Qura is not used as reference for ibadah e.g. beginning of saum (fasting), Eid al-Fitr, and Eid al-Adha. 15 | 16 | ## Usage example 17 | 18 | Latitude and longitude are in degrees, positive values for north and east respectively, negative values for south and west respectively. More examples are available in `example-*.py`. 19 | 20 | ```python 21 | from iclib import salat 22 | import datetime 23 | 24 | date = datetime.date.today() 25 | c = (salat.TimeCalculator().date(date) 26 | # latitude, longitude, altitude/height, timezone 27 | .location(-6.38043079, 106.85337984, 0, +7) 28 | .method('egypt')) 29 | t = c.calculate() 30 | for i in t: 31 | print(i) # as datetime.time 32 | 33 | # other styles 34 | print(t.zuhr) # as datetime.time 35 | print(t.get_time(salat.ASR)) # as datetime.time 36 | print(t.get_hms(salat.MAGHRIB)) # as tuple of int (hour, minute, second) 37 | print(t.get_hm(salat.ISHA)) # as tuple of int (hour, minute) 38 | ``` 39 | 40 | ```python 41 | from iclib import qibla 42 | 43 | lat = -6.169777778 44 | lng = 106.8307333 45 | print(qibla.direction(lat, lng)) # in degrees from the north (clock-wise) 46 | print(qibla.direction_dms(lat, lng)) # deg, min, sec (as tuple) 47 | print(qibla.direction_str(lat, lng)) # deg° min' sec" (as str) 48 | ``` 49 | 50 | ```python 51 | from iclib.hijri import ummqura 52 | 53 | print(ummqura.to_gregorian(1436, 1, 1)) # year, month, day 54 | print(ummqura.from_gregorian(2015, 1, 1)) # year, month, day 55 | ``` 56 | 57 | ## Calculation method choices 58 | 59 | For Asr, you can choose between "Majority" and "Hanafi". According to the study of the majority of scholars (_Jumhur Ulama_), including Imam Shafi'i, based on Hadith Asr is when the length of shadow **equals** to the length of the object, plus the length of the shadow at midday. However, according to the study of Imam Hanafi, the length of shadow is **twice** the length of the object, plus the length of the shadow at midday. 60 | 61 | For Fajr and Isha, there are difference (scientific) opinions about the angle of the Sun (below the horizon) at those time. These are some Islamic institution standards you can choose. Some is not implemented yet, but you can set it manually. _(Copied from [itl-java](https://github.com/fikr4n/itl-java) README file)_ 62 | 63 | - **Egyptian General Authority of Survey**; usually used in Indonesia, Iraq, Jordan, Lebanon, Malaysia, Singapore, Syria, parts of Africa, and parts of United States. 64 | - **University of Islamic Sciences**, Karachi (Shafi'i); usually used in Iran, Kuwait, and parts of Europe. 65 | - **University of Islamic Sciences**, Karachi (Hanafi); usually used in Afghanistan, Bangladesh, and India. 66 | - **Islamic Society of North America**; usually used in Canada, Parts of UK, and parts of United States. 67 | - **Muslim World League (MWL)**; usually used in parts of Europe, Far East, and parts of United States. 68 | - **Umm Al-Qurra University**; usually used in Saudi Arabia. 69 | - Fixed Ishaa Angle Interval (always 90); usually used in Bahrain, Oman, Qatar, United Arab Emirates. 70 | 71 | There are locations near the poles having extreme latitude where some salat times cannot be calculated. For example, if location L is always night on date D1 till D2, we cannot calculate sunrise and maghrib for those days. Those extreme latitudes accross a (gregorian) year is displayed in black and white in attached images `generate_extreme_*.png`. Solution for these locations is by using estimation or approach. Please read the literatures about this. 72 | 73 | ![egypt](https://raw.githubusercontent.com/fikr4n/iclib-python/master/generate_extreme_egypt.png) 74 | _Extreme latitude based on 'egypt' method_ 75 | 76 | More about prayer times, you can learn from Kitabs of Fiqih or online resource. 77 | 78 | ## Further reading 79 | 80 | - Waktu Shalat (Bahasa Indonesia) [1](http://rumaysho.com/shalat/waktu-shalat-1-shalat-zhuhur-2932.html) [2](http://rumaysho.com/shalat/waktu-shalat-2-shalat-ashar-2936.html) [3](http://rumaysho.com/shalat/waktu-shalat-3-shalat-maghrib-2940.html) [4](http://rumaysho.com/shalat/waktu-shalat-4-shalat-isya-2944.html) [5](http://rumaysho.com/shalat/waktu-shalat-5-shalat-shubuh-2948.html) 81 | 82 | --- 83 | 84 | _We need your dua and support_ 85 | 86 | **Salam and have fun!** 87 | -------------------------------------------------------------------------------- /Tissot_indicatrix_world_map_equirectangular_proj_by_Eric_Gaba_from_wikimedia.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fikr4n/iclib-python/278698a35777046ee34b082d817763e1bbeaad17/Tissot_indicatrix_world_map_equirectangular_proj_by_Eric_Gaba_from_wikimedia.png -------------------------------------------------------------------------------- /example-hijri.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | from iclib.hijri import ummqura 4 | 5 | 6 | def ummqura_gregorian(): 7 | d = (1436, 1, 1) 8 | print(d, '->', ummqura.to_gregorian(*d)) 9 | 10 | def ummqura_gregorian_first(): 11 | print(ummqura.to_gregorian(1420, 1, 1)) 12 | 13 | def ummqura_gregorian_last(): 14 | print(ummqura.to_gregorian(1450, 12, 30)) 15 | 16 | def gregorian_ummqura(): 17 | d = (2015, 1, 1) 18 | print(d, '->', ummqura.from_gregorian(*d)) 19 | 20 | def gregorian_ummqura_first(): 21 | print(ummqura.from_gregorian(1999, 4, 17)) 22 | 23 | def gregorian_ummqura_last(): 24 | print(ummqura.from_gregorian(2029, 5, 14)) 25 | 26 | loc = sorted(locals().items()) 27 | for k,v in loc: 28 | if not k.startswith('_') and callable(v): 29 | print('-' * 5, k, '-' * 5) 30 | v() 31 | print() 32 | 33 | -------------------------------------------------------------------------------- /example-qibla.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | from iclib import qibla 4 | 5 | 6 | def istiqlal(): 7 | lat = -6.169777778 8 | lng = 106.8307333 9 | print(qibla.direction(lat, lng)) 10 | print(qibla.direction_dms(lat, lng)) 11 | print(qibla.direction_str(lat, lng)) 12 | 13 | def yogyakarta(): 14 | lat = -(7 + 48 / 60.0) 15 | lng = 110 + 21 / 60.0 16 | print(qibla.direction(lat, lng)) 17 | print(qibla.direction_dms(lat, lng)) 18 | print(qibla.direction_str(lat, lng)) 19 | 20 | def nearnorthpole(): 21 | lat = 89 22 | lng = 39.82616111 23 | print(qibla.direction(lat, lng)) 24 | print(qibla.direction_dms(lat, lng)) 25 | print(qibla.direction_str(lat, lng)) 26 | 27 | def nearsouthpole(): 28 | lat = -89 29 | lng = 39.82616111 30 | print(qibla.direction(lat, lng)) 31 | print(qibla.direction_dms(lat, lng)) 32 | print(qibla.direction_str(lat, lng)) 33 | 34 | def makkah_east(): 35 | lat = 21.42250833 36 | lng = 40 37 | print(qibla.direction(lat, lng)) 38 | print(qibla.direction_dms(lat, lng)) 39 | print(qibla.direction_str(lat, lng)) 40 | 41 | def makkah_west(): 42 | lat = 21.42250833 43 | lng = 39 44 | print(qibla.direction(lat, lng)) 45 | print(qibla.direction_dms(lat, lng)) 46 | print(qibla.direction_str(lat, lng)) 47 | 48 | loc = sorted(locals().items()) 49 | for k,v in loc: 50 | if not k.startswith('_') and callable(v): 51 | print('-' * 5, k, '-' * 5) 52 | v() 53 | print() 54 | 55 | -------------------------------------------------------------------------------- /example-salat.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | from iclib import salat 4 | import datetime as dt 5 | 6 | 7 | date = dt.date.today() 8 | print('Date:', date) 9 | print() 10 | 11 | def _egypt_init(): 12 | c = salat.TimeCalculator().date(date) \ 13 | .location(-6.38043079, 106.85337984, 0, 7) \ 14 | .method('egypt') 15 | return date, c.calculate() 16 | 17 | def egypt_gettime(): 18 | date, t = _egypt_init() 19 | for i in (salat.FAJR, salat.SUNRISE, salat.ZUHR, salat.ASR, 20 | salat.MAGHRIB, salat.ISHA): 21 | print(t.get_time(i).strftime('%H:%M')) 22 | 23 | def egypt_property_withsec(): 24 | date, t = _egypt_init() 25 | t.use_second = True 26 | print(t.fajr) 27 | print(t.sunrise) 28 | print(t.zuhr) 29 | print(t.asr) 30 | print(t.maghrib) 31 | print(t.isha) 32 | 33 | def egypt_iter_noadjust(): 34 | c = salat.TimeCalculator().date(date) \ 35 | .location(-6.38043079, 106.85337984, 0, 7) \ 36 | .method('egypt', None, {}) 37 | t = c.calculate() 38 | for i in t: 39 | print(i) 40 | 41 | def muhammadiyah(): 42 | c = salat.TimeCalculator().date(date) \ 43 | .location(-6.38043079, 106.85337984, 0, 7) \ 44 | .method('muhammadiyah') 45 | for i in c.calculate(): 46 | print(i) 47 | 48 | def mwl_noadjust(): 49 | c = salat.TimeCalculator().date(date) \ 50 | .location(-6.38043079, 106.85337984, 0, 7) \ 51 | .method('mwl', 'majority', {}) 52 | for i in c.calculate(): 53 | print(i) 54 | 55 | def mwl_hanafi_noadjust(): 56 | c = salat.TimeCalculator().date(date) \ 57 | .location(-6.38043079, 106.85337984, 0, 7) \ 58 | .method('mwl', 'hanafi', {}) 59 | for i in c.calculate(): 60 | print(i) 61 | 62 | def mwl_noadjust_100m(): 63 | c = salat.TimeCalculator().date(date) \ 64 | .location(-6.38043079, 106.85337984, 100, 7) \ 65 | .method('mwl', 'majority', {}) 66 | for i in c.calculate(): 67 | print(i) 68 | 69 | def mwl_1jan2015(): 70 | c = salat.TimeCalculator().gregorian_date(2015, 1, 1) \ 71 | .location(-6.38043079, 106.85337984, 0, 7) \ 72 | .method('mwl') 73 | for i in c.calculate(): 74 | print(i) 75 | 76 | def mwl_1jan2015_tomorrow(): 77 | c = salat.TimeCalculator().gregorian_date(2015, 1, 1) \ 78 | .location(-6.38043079, 106.85337984, 0, 7) \ 79 | .method('mwl') 80 | c.date_relative(+1) 81 | for i in c.calculate(): 82 | print(i) 83 | 84 | 85 | loc = sorted(locals().items()) 86 | for k,v in loc: 87 | if not k.startswith('_') and callable(v): 88 | print('-' * 5, k, '-' * 5) 89 | v() 90 | print() 91 | -------------------------------------------------------------------------------- /generate_extreme.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | from iclib import salat 3 | import datetime as dt 4 | import PIL.Image 5 | import PIL.ImageDraw 6 | import PIL.ImageFont 7 | from PIL.ImageColor import getrgb as rgb 8 | import sys 9 | 10 | def xlen(start, stop, step): 11 | """Number of items `frange` will generate""" 12 | return sum(1 for _ in frange(start, stop, step)) 13 | 14 | def frange(start, stop, step): 15 | """Float version of `range`""" 16 | f = 1 / step 17 | return (i / f for i in range(int(start * f), int(stop * f), int(step * f))) 18 | 19 | def to_color(times): 20 | """Color representation of extreme (could not calculate) salat times""" 21 | m = times.times 22 | # fajr (½red), isha (½red), sunrise (½green), maghrib (½green), asr (blue) 23 | r1, r2, g1, g2, b = 0, 0, 0, 0, 0 24 | if m[salat.FAJR] == inf: r1 = 0x44 25 | elif m[salat.FAJR] == -inf: r1 = -0x44 26 | if m[salat.ISHA] == inf: r2 = -0x44 27 | elif m[salat.ISHA] == -inf: r2 = 0x44 28 | if m[salat.SUNRISE] == inf: g1 = 0x44 29 | elif m[salat.SUNRISE] == -inf: g1 = -0x44 30 | if m[salat.MAGHRIB] == inf: g2 = -0x44 31 | elif m[salat.MAGHRIB] == -inf: g2 = 0x44 32 | if m[salat.ASR] == inf: b = -0x88 33 | elif m[salat.ASR] == -inf: b = 0x88 34 | return r1, r2, g1, g2, b 35 | 36 | METHOD = sys.argv[1] 37 | DAYS = (0, 365, 5/1) # horizontal frange 38 | WIDTH = xlen(*DAYS) 39 | LATS = (90, -90 - 1/1, -1/1) # vertical frange 40 | HEIGHT = xlen(*LATS) 41 | inf = float('inf') 42 | 43 | if __name__ == '__main__': 44 | pixels = [] 45 | c = salat.TimeCalculator().method(METHOD) 46 | 47 | for lat in frange(*LATS): # horizontal line from top to bottom 48 | if lat % 15 == 0: # draw only horizontal separator 49 | pixels.extend((rgb('#333333'),) * (6 * WIDTH + 5)) 50 | continue 51 | 52 | c.location(lat, 0, 0, 0) 53 | row = [to_color(c.date(dt.datetime(2015, 1, 1) + dt.timedelta(yday)).calculate()) 54 | for yday in frange(*DAYS)] 55 | for p in row: # fajr 56 | pixels.append((p[0]*2 + 0x88,) * 3) 57 | pixels.append(rgb('#333333')) 58 | for p in row: # isha 59 | pixels.append((p[1]*2 + 0x88,) * 3) 60 | pixels.append(rgb('#333333')) 61 | for p in row: # sunrise 62 | pixels.append((p[2]*2 + 0x88,) * 3) 63 | pixels.append(rgb('#333333')) 64 | for p in row: # maghrib 65 | pixels.append((p[3]*2 + 0x88,) * 3) 66 | pixels.append(rgb('#333333')) 67 | for p in row: # asr 68 | pixels.append((p[4] + 0x88,) * 3) 69 | pixels.append(rgb('#333333')) 70 | for p in row: # all 71 | pixels.append((p[0] + p[1] + 0x88, p[2] + p[3] + 0x88, p[4] + 0x88)) 72 | ximg = PIL.Image.new('RGB', (6 * WIDTH + 5, HEIGHT)) 73 | ximg.putdata(pixels) 74 | draw = PIL.ImageDraw.Draw(ximg) 75 | font = PIL.ImageFont.load_default() 76 | for i, name in enumerate(('FAJR', 'ISHA', 'SUNRISE', 'MAGRIB', 'ASR', 'MIXED')): 77 | w, h = draw.textsize(name, font) 78 | draw.text(((i+0.5) * (WIDTH+1) - w/2, HEIGHT/2 - h/2), name, 79 | fill=(0xff, 0xff, 0xff), font=font) 80 | 81 | world = PIL.Image.open('Tissot_indicatrix_world_map_equirectangular_proj_by_Eric_Gaba_from_wikimedia.png', 'r') 82 | world = world.resize((WIDTH*2, HEIGHT), PIL.Image.ANTIALIAS) 83 | draw = PIL.ImageDraw.Draw(world) 84 | for y in range(0, world.size[1], 15): 85 | draw.line([0, y, world.size[0], y], rgb('#333333'), 1) 86 | 87 | img = PIL.Image.new('RGB', (ximg.size[0] + world.size[0], HEIGHT)) 88 | img.paste(world, (0, 0)) 89 | img.paste(ximg, (world.size[0], 0)) 90 | img.save('generate_extreme_' + METHOD + '.png') 91 | 92 | -------------------------------------------------------------------------------- /generate_extreme_egypt.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fikr4n/iclib-python/278698a35777046ee34b082d817763e1bbeaad17/generate_extreme_egypt.png -------------------------------------------------------------------------------- /generate_extreme_isna.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fikr4n/iclib-python/278698a35777046ee34b082d817763e1bbeaad17/generate_extreme_isna.png -------------------------------------------------------------------------------- /generate_extreme_karachi.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fikr4n/iclib-python/278698a35777046ee34b082d817763e1bbeaad17/generate_extreme_karachi.png -------------------------------------------------------------------------------- /generate_extreme_muhammadiyah.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fikr4n/iclib-python/278698a35777046ee34b082d817763e1bbeaad17/generate_extreme_muhammadiyah.png -------------------------------------------------------------------------------- /generate_extreme_mwl.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fikr4n/iclib-python/278698a35777046ee34b082d817763e1bbeaad17/generate_extreme_mwl.png -------------------------------------------------------------------------------- /iclib/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fikr4n/iclib-python/278698a35777046ee34b082d817763e1bbeaad17/iclib/__init__.py -------------------------------------------------------------------------------- /iclib/formula.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2015 Fikrul Arif 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 | # Convention for internal/basic formula: 16 | # - short param name, mid-length method name 17 | # - no structure/class, only basic/primitives known in majority of languages 18 | # - procedural 19 | # - constants only for very limited choices (asr shadow ratio) 20 | # - no param (type, value, range, etc) checking 21 | # - no exception raising/throwing 22 | # - use decimal separator for number in floating-point-aware division 23 | # - no method overloading 24 | # - casing follows language convention 25 | # Note: 26 | # - all angles are "currently" in degrees instead of radians 27 | # - all length (actually only h) are in meters 28 | # - all times are in hours 29 | # - month, day, and weekday start from 1 (Muharram, January, Ahad/Sunday) 30 | """Basic formula of calculation 31 | 32 | Prayer time calculation functions return numbers in hours, 0 means midnight, 33 | 13.5 means 13:30, etc. They have some of these parameters, each of them is 34 | number: 35 | lat - latitude in degrees 36 | lng - longitude in degrees 37 | h - observer's altitude/height from sealevel in meters 38 | tz - timezone 39 | et - Equation of Time (eq_time function) 40 | ds - declination of the Sun (decl_sun function) 41 | t_zuhr - Zuhr time in hours (zuhr function) 42 | fajr_angle - angle for Fajr time 43 | isha_angle - angle for Isha time 44 | """ 45 | import math 46 | 47 | 48 | ASR_RATIO_MAJORITY = 1 49 | ASR_RATIO_HANAFI = 2 50 | 51 | 52 | def zuhr (lng, tz, et): 53 | return 12 + tz - lng / 15.0 - et 54 | 55 | def asr (t_zuhr, lat, ds, asr_ratio): 56 | alt = _acot_deg(asr_ratio + _tan_deg(abs(ds - lat))) # altitude of the sun 57 | return t_zuhr + hour_angle(lat, alt, ds) / 15.0 58 | 59 | def maghrib(t_zuhr, lat, ds, h): 60 | alt = -0.8333 - 0.0347 * math.sqrt(h) 61 | return t_zuhr + hour_angle(lat, alt, ds) / 15.0 62 | 63 | def isha (t_zuhr, lat, ds, isha_angle): 64 | alt = -isha_angle 65 | return t_zuhr + hour_angle(lat, alt, ds) / 15.0 66 | 67 | def fajr (t_zuhr, lat, ds, fajr_angle): 68 | alt = -fajr_angle 69 | return t_zuhr - hour_angle(lat, alt, ds) / 15.0 70 | 71 | def sunrise(t_zuhr, lat, ds, h): 72 | alt = -0.8333 - 0.0347 * math.sqrt(h) # equals to maghrib 73 | return t_zuhr - hour_angle(lat, alt, ds) / 15.0 74 | 75 | def hour_angle(lat, alt, ds): 76 | """Return hour angle in degrees""" 77 | cos_ha = ((_sin_deg(alt) - _sin_deg(lat) * _sin_deg(ds)) 78 | / ( _cos_deg(lat) * _cos_deg(ds))) 79 | if cos_ha < -1: return -float('inf') 80 | if cos_ha > 1: return float('inf') 81 | return _acos_deg(cos_ha) 82 | 83 | def eq_time(jd): 84 | """Return Equation of Time in hours""" 85 | u = (jd - 2451545) / 36525.0 86 | l0 = 280.46607 + 36000.7698 * u # average longitude of the sun in degrees 87 | return ( 88 | -(1789 + 237 * u) * _sin_deg(l0) 89 | - (7146 - 62 * u) * _cos_deg(l0) 90 | + (9934 - 14 * u) * _sin_deg(2 * l0) 91 | - (29 + 5 * u) * _cos_deg(2 * l0) 92 | + (74 + 10 * u) * _sin_deg(3 * l0) 93 | + (320 - 4 * u) * _cos_deg(3 * l0) 94 | - 212 * _sin_deg(4 * l0)) / 60000.0 95 | 96 | def decl_sun(jd): 97 | """Return declination of the Sun in degrees""" 98 | t = 2 * math.pi * (jd - 2451545) / 365.25 # angle of date 99 | return (0.37877 100 | + 23.264 * _sin_deg( 57.297 * t - 79.547) 101 | + 0.3812 * _sin_deg(2 * 57.297 * t - 82.682) 102 | + 0.17132 * _sin_deg(3 * 57.297 * t - 59.722)) 103 | 104 | def gregorian_to_jd(y, m, d): 105 | """Return Julian Day of a Gregorian or Julian date 106 | 107 | Negative Julian Day (i.e. y < -4712 or 4713 BC) is not supported. 108 | 109 | Param: 110 | y as int - year 111 | m as int - month [1..12] 112 | d as int - day [1..31] 113 | """ 114 | if y < -4712: raise ValueError('year < -4712 is not supported') 115 | 116 | if m <= 2: 117 | m += 12; y -= 1 118 | if y > 1582 or (y == 1582 and (m > 10 or (m == 10 and d >= 15))): 119 | # first gregorian is 15-oct-1582 120 | a = math.floor(y / 100.0) 121 | b = 2 + math.floor(a / 4.0) - a 122 | else: # invalid dates (5-14) are also considered as julian 123 | b = 0 124 | abs_jd = (1720994.5 + math.floor(365.25 * y) + math.floor(30.6001 * (m + 1)) 125 | + d + b) 126 | return abs_jd 127 | 128 | def jd_to_gregorian(jd): 129 | """Return Gregorian or Julian date of Julian Day 130 | 131 | Negative Julian Day < -0.5 is not supported. 132 | 133 | Return: 134 | int - year 135 | int - month [1..12] 136 | int - day [1..31] 137 | """ 138 | if jd < -0.5: raise ValueError('Julian Day < -0.5 is not supported') 139 | 140 | jd1 = jd + 0.5 141 | z = math.floor(jd1) 142 | f = jd1 - z 143 | if z < 2299161: 144 | a = z 145 | else: 146 | aa = math.floor((z - 1867216.25) / 36524.25) 147 | a = z + 1 + aa - math.floor(aa / 4.0) 148 | b = a + 1524 149 | c = math.floor((b - 122.1) / 365.25) 150 | d = math.floor(365.25 * c) 151 | e = math.floor((b - d) / 30.6001) 152 | day = b - d - math.floor(30.6001 * e) + f 153 | month = e - 1 if e < 14 else e - 13 154 | year = c - 4715 if month <= 2 else c - 4716 155 | return (int(year), int(month), int(day)) 156 | 157 | def jd_to_weekday(jd): 158 | """Return weekday of Julian Day 159 | 160 | Return: 161 | int - weekday [1..7] where 1 is Ahad/Sunday 162 | """ 163 | return int(math.floor(jd + 1.5) % 7) + 1 164 | 165 | def adjust_jd_hour(jd, hours): 166 | """Return Julian Day with added hours""" 167 | return jd + hours / 24.0 168 | 169 | def qibla(lat, lng): 170 | """Return qibla direction in degrees from the north (clock-wise) 171 | 172 | Param: 173 | lat as number - latitude in degrees 174 | lng as number - longitude in degrees 175 | 176 | Return: 177 | number - 0 means north, 90 means east, 270 means west, etc 178 | """ 179 | lng_a = 39.82616111 180 | lat_a = 21.42250833 181 | deg = _atan2_deg(_sin_deg(lng_a - lng), 182 | _cos_deg(lat) * _tan_deg(lat_a) 183 | - _sin_deg(lat) * _cos_deg(lng_a - lng)) 184 | return deg if deg >= 0 else deg + 360 185 | 186 | def _sin_deg(deg): 187 | return math.sin(math.radians(deg)) 188 | 189 | def _cos_deg(deg): 190 | return math.cos(math.radians(deg)) 191 | 192 | def _acos_deg(x_r): 193 | return math.degrees(math.acos(x_r)) 194 | 195 | def _tan_deg(deg): 196 | return math.tan(math.radians(deg)) 197 | 198 | def _acot_deg(x_y): 199 | return math.degrees(math.atan(1.0 / x_y)) 200 | 201 | def _atan2_deg(y, x): 202 | return math.degrees(math.atan2(y, x)) 203 | 204 | -------------------------------------------------------------------------------- /iclib/hijri/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fikr4n/iclib-python/278698a35777046ee34b082d817763e1bbeaad17/iclib/hijri/__init__.py -------------------------------------------------------------------------------- /iclib/hijri/ummqura.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2015 Fikrul Arif 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 | """Convert date to Umm al-Qura calendar and vice versa""" 15 | 16 | from .. import formula 17 | 18 | 19 | def from_gregorian(y, m, d): 20 | """Convert from Gregorian date 21 | 22 | This is valid only for 1420-1450 AH (April 17 1999 - May 14 2029). 23 | 24 | Param: 25 | y as int - year 26 | m as int - month [1..12] 27 | d as int - day of month [1..31] 28 | 29 | Return: 30 | int - year 31 | int - month [1..12] 32 | int - day of month [1..30] 33 | int - number of days in the Hijri month 34 | """ 35 | # valid from 1420 AH (1999-04-17 CE) to 1450 AH (2029-05-14 CE) 36 | jd = int(formula.gregorian_to_jd(y, m, d) + 0.5) # jd midday 37 | accu = 2451286 # jd of 1999-04-17 midday 38 | i = -1 39 | while accu <= jd: 40 | i += 1 41 | accu += _month_len[i] + 29 42 | if i == -1: raise IndexError(i) 43 | month_start = accu - _month_len[i] - 29 44 | # here i is index where the month we're looking for is 45 | h_year = i // 12 + 1420 46 | h_month = i % 12 + 1 47 | h_day = jd - month_start + 1 48 | return (h_year, h_month, h_day, _month_len[i] + 29) 49 | 50 | def to_gregorian(y, m, d): 51 | """Convert to Gregorian date 52 | 53 | This is valid only for 1420-1450 AH (April 17 1999 - May 14 2029). 54 | 55 | Param: 56 | y as int - year 57 | m as int - month [1..12] 58 | d as int - day of month [1..30] 59 | 60 | Return: 61 | int - year 62 | int - month [1..12] 63 | int - day of month [1..31] 64 | """ 65 | index = (y - 1420) * 12 + m - 1 66 | if index < 0 or index > len(_month_len): raise IndexError(index) 67 | jd = 2451285.5 + sum(i + 29 for i in _month_len[:index]) + d - 1 68 | return formula.jd_to_gregorian(jd) 69 | 70 | _month_len = (0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 71 | 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 72 | 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 73 | 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 74 | 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 75 | 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 76 | 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 77 | 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 78 | 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 79 | 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 80 | 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 81 | 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 82 | 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 83 | 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 84 | 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 85 | 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 86 | 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 87 | 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 88 | 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 89 | 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 90 | 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 91 | 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 92 | 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 93 | 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 94 | 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 95 | 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 96 | 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 97 | 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 98 | 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 99 | 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 100 | 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1) 101 | 102 | -------------------------------------------------------------------------------- /iclib/qibla.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2015 Fikrul Arif 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | """Qibla direction calculator""" 16 | 17 | from . import formula 18 | from .util import dms, dms_str 19 | 20 | 21 | def direction(lat, lng): 22 | return formula.qibla(lat, lng) 23 | direction.__doc__ = formula.qibla.__doc__ 24 | 25 | def direction_dms(lat, lng): 26 | """Calculate qibla direction as 3-tuple of degree-minute-second 27 | 28 | Degree and arc minute is int, but arc second can be a floating-point number. 29 | """ 30 | return dms(formula.qibla(lat, lng)) 31 | 32 | def direction_str(lat, lng, prec=0): 33 | """Like direction_dms, but formatted as str 'deg° min′ sec″' 34 | 35 | Param: 36 | lat 37 | lng 38 | prec as int - number of decimal places for the arc second 39 | """ 40 | return dms_str(formula.qibla(lat, lng), prec) 41 | 42 | -------------------------------------------------------------------------------- /iclib/salat.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2015 Fikrul Arif 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 | """Prayer times calculator""" 15 | 16 | from . import formula 17 | from .util import hms, hm 18 | import datetime 19 | import math 20 | import collections 21 | 22 | 23 | STANDARD_ANGLES = { 24 | # (fajr_deg, isha_deg) 25 | 'mwl': (18, 17), 26 | 'isna': (15, 15), 27 | 'egypt': (19.5, 17.5), 28 | 'karachi': (18, 18), 29 | 'muhammadiyah': (20, 18), 30 | } 31 | 32 | N = 6 33 | FAJR, SUNRISE, ZUHR, ASR, MAGHRIB, ISHA = range(N) 34 | 35 | 36 | class TimeCalculator(object): 37 | 38 | def method(self, angle, asr_ratio=None, adjustments={ZUHR: 2.0/60}): 39 | """Set method and adjustment of calculation 40 | 41 | Standard angle names for param angle are available in STANDARD_ANGLES. 42 | Value for asr_ratio can be 'hanafi' or anything else (default value), 43 | such as 'majority' or None, which means majority of scholars except 44 | Imam Hanafi. Adjustment is addition to the result, use ZUHR, ASR, etc as 45 | the key. By default it adjusts Zuhr time by 2 minutes to wait the Sun 46 | turn down to the west. 47 | 48 | Param: 49 | angle as str or 2-tuple of number - Fajr and Isha angle 50 | asr_ratio - ratio of object's shadow to determine Asr time 51 | adjustment as dict of int to number - result adjustment 52 | 53 | Return: 54 | self for chaining 55 | """ 56 | if type(angle) is str: 57 | self.fajr_angle, self.isha_angle = STANDARD_ANGLES[angle] 58 | else: 59 | self.fajr_angle, self.isha_angle = angle 60 | if asr_ratio == 'hanafi': 61 | self.asr_ratio = formula.ASR_RATIO_HANAFI 62 | else: 63 | self.asr_ratio = formula.ASR_RATIO_MAJORITY 64 | self.adjustments = tuple(adjustments.get(k, 0) for k in range(N)) 65 | return self 66 | 67 | def location(self, lat, lng, h, tz): 68 | """Set the location 69 | 70 | Param: 71 | lat as number - latitude in degrees 72 | lng as number - longitude in degrees 73 | h as number - altitude/height of the place in meters 74 | tz as number - timezone in hours, x means UTC+x 75 | 76 | Return: 77 | self for chaining 78 | """ 79 | self.lat = lat 80 | self.lng = lng 81 | self.h = h 82 | if isinstance(tz, datetime.tzinfo): 83 | self.tz = tz.utcoffset(None).total_seconds() / 3600.0 84 | else: 85 | self.tz = tz 86 | return self 87 | 88 | def date(self, date): 89 | """Set the date 90 | 91 | Param: 92 | date as datetime.date 93 | 94 | Return: 95 | self for chaining 96 | """ 97 | self.jd = formula.gregorian_to_jd(date.year, date.month, date.day) 98 | return self 99 | 100 | def gregorian_date(self, y, m, d): 101 | """Set the date, like method date(self, date) 102 | 103 | Param: 104 | y as int - year 105 | m as int - month [1..12] 106 | d as int - day of month [1..31] 107 | 108 | Return: 109 | self for chaining 110 | """ 111 | self.jd = formula.gregorian_to_jd(y, m, d) 112 | return self 113 | 114 | def date_relative(self, days): 115 | """Add the date by days""" 116 | self.jd += days 117 | return self 118 | 119 | def calculate(self): 120 | """Calculate the prayer times 121 | 122 | This method can be called several times. For example, you set the date 123 | and call this method, update the date to tomorrow and call this method. 124 | 125 | Return: 126 | result as Times 127 | """ 128 | # julian day of local midday (minus timezone, plus 12 hours) 129 | jd = formula.adjust_jd_hour(self.jd, -self.tz + 12) 130 | ds = formula.decl_sun(jd) 131 | transit = formula.zuhr(self.lng, self.tz, formula.eq_time(jd)) 132 | lat = self.lat 133 | return Times([i + adj for i,adj in zip( 134 | ( 135 | formula.fajr (transit, lat, ds, self.fajr_angle), 136 | formula.sunrise(transit, lat, ds, self.h), 137 | transit, 138 | formula.asr (transit, lat, ds, self.asr_ratio), 139 | formula.maghrib(transit, lat, ds, self.h), 140 | formula.isha (transit, lat, ds, self.isha_angle)), 141 | self.adjustments)]) 142 | 143 | inf = float('inf') 144 | 145 | class Times(object): 146 | """Result of TimeCalculator""" 147 | 148 | def __init__(self, times): 149 | self.times = times 150 | self.use_second = False 151 | if times[SUNRISE] == -inf or times[MAGHRIB] == inf: 152 | times[ZUHR] = inf 153 | times[ASR] = inf 154 | 155 | def get_time(self, i): 156 | """Return the time as datetime.time 157 | 158 | The value of self.use_second is considered. 159 | 160 | Param: 161 | i as int - ZUHR, ASR, etc 162 | """ 163 | # negative hours will raise exception 164 | try: 165 | if self.use_second: return datetime.time(*self.get_hms(i)) 166 | else: return datetime.time(*self.get_hm(i)) 167 | except TypeError: 168 | return None 169 | 170 | def get_hms(self, i): 171 | """Return the time as 3-tuple of hour-minute-second 172 | 173 | Param: 174 | i as int - ZUHR, ASR, etc 175 | """ 176 | return hms(self.times[i]) 177 | 178 | def get_hm(self, i): 179 | """Return the time as 2-tuple of hour-minute 180 | 181 | Param: 182 | i as int - ZUHR, ASR, etc 183 | """ 184 | return hm(self.times[i]) 185 | 186 | def __iter__(self): 187 | return iter(self.get_time(i) for i in range(len(self.times))) 188 | 189 | _names = ('fajr', 'sunrise', 'zuhr', 'asr', 'maghrib', 'isha') 190 | def __getattr__(self, name): 191 | if name in self._names: 192 | return self.get_time(self._names.index(name)) 193 | else: 194 | raise AttributeError("'{}' object has no attribute '{}'". 195 | format(self.__class__.__name__, name)) 196 | -------------------------------------------------------------------------------- /iclib/util.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2015 Fikrul Arif 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | import math 16 | 17 | 18 | def dms(deg): 19 | """Convert degree to degree-minute-second 20 | 21 | If deg is negative, all values of tuple are negative or 0. 22 | """ 23 | seconds = deg * 3600 24 | d = seconds / 3600 25 | m = math.fmod(seconds, 3600) / 60 26 | s = math.fmod(seconds, 60) 27 | return (int(d), int(m), s) 28 | 29 | def dms_str(deg, prec): 30 | d, m, s = dms(deg) 31 | if deg < 0: 32 | return '-{}° {}′ {:.{}f}″'.format(-d, -m, -s, prec) 33 | else: 34 | return '{}° {}′ {:.{}f}″'.format(d, m, s, prec) 35 | 36 | def hms(hours): 37 | """Convert hours to hour-minute-second 38 | 39 | If hours is negative, only hour of the tuple is negative. 40 | """ 41 | if math.isinf(hours): 42 | return None 43 | seconds = int(math.ceil(hours * 3600)) 44 | h, seconds = divmod(seconds, 3600) 45 | m, seconds = divmod(seconds, 60) 46 | return (h, m, seconds) 47 | 48 | def hm(hours): 49 | """Convert hours to hour-minute 50 | 51 | If hours is negative, only hour of the tuple is negative. 52 | """ 53 | if math.isinf(hours): 54 | return None 55 | minutes = int(math.ceil(hours * 60)) 56 | h, minutes = divmod(minutes, 60) 57 | return (h, minutes) 58 | 59 | --------------------------------------------------------------------------------