Metadata-Version: 2.4
Name: tr-deprem
Version: 0.1.0
Summary: Turkish earthquake data in Python: one client for AFAD, Kandilli (KOERI), USGS and EMSC with de-duplication, province lookup, b-value statistics and a Turkish CLI.
Author-email: Yusuf Eminoğlu <yusufeminoglu@gmail.com>
License-Expression: MIT
Project-URL: Homepage, https://github.com/YusufEminoglu/tr_deprem_sdk
Project-URL: Repository, https://github.com/YusufEminoglu/tr_deprem_sdk
Project-URL: Issues, https://github.com/YusufEminoglu/tr_deprem_sdk/issues
Project-URL: Changelog, https://github.com/YusufEminoglu/tr_deprem_sdk/blob/main/CHANGELOG.md
Keywords: earthquake,deprem,seismology,turkey,turkiye,afad,kandilli,koeri,usgs,emsc,fdsn,gutenberg-richter,b-value,geojson,gis
Classifier: Development Status :: 4 - Beta
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Operating System :: OS Independent
Classifier: Environment :: Console
Classifier: Natural Language :: Turkish
Classifier: Natural Language :: English
Classifier: Topic :: Scientific/Engineering :: GIS
Classifier: Topic :: Scientific/Engineering :: Physics
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: Developers
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: pandas
Requires-Dist: pandas>=1.3.0; extra == "pandas"
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"
Dynamic: license-file

<div align="center">

# tr-deprem

[![PyPI version](https://img.shields.io/pypi/v/tr-deprem.svg?color=10b981)](https://pypi.org/project/tr-deprem/)
[![Python version support](https://img.shields.io/pypi/pyversions/tr-deprem.svg?color=3b82f6)](https://pypi.org/project/tr-deprem/)
[![CI](https://github.com/YusufEminoglu/tr_deprem_sdk/actions/workflows/ci.yml/badge.svg)](https://github.com/YusufEminoglu/tr_deprem_sdk/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://github.com/YusufEminoglu/tr_deprem_sdk/blob/main/LICENSE)
[![Code style: Ruff](https://img.shields.io/badge/code%20style-ruff-D7FF64.svg)](https://docs.astral.sh/ruff/)
[![Test Coverage](https://img.shields.io/badge/coverage-98%25-brightgreen.svg)](#development--geliştirme)
[![Dependencies: none](https://img.shields.io/badge/dependencies-none-brightgreen.svg)](https://pypi.org/project/tr-deprem/)

**Türkiye deprem verisi için Python istemcisi: AFAD, Kandilli, USGS ve EMSC tek arayüzde.**
**Turkish earthquake data in Python: AFAD, Kandilli, USGS and EMSC through one interface.**

[Türkçe](#türkçe) • [English](#english) • [PyPI](https://pypi.org/project/tr-deprem/) • [Issues](https://github.com/YusufEminoglu/tr_deprem_sdk/issues)

</div>

> **Uyarı / Disclaimer:** `tr-deprem` resmi bir deprem uyarı veya erken uyarı sistemi
> **değildir**. Veriler kaynaklardan gecikmeli gelir ve sonradan revize edilebilir. Resmi
> bilgi ve afet durumunda talimatlar için [AFAD](https://www.afad.gov.tr/) ve
> [Kandilli Rasathanesi](http://www.koeri.boun.edu.tr/) duyurularını izleyin.
> *This is not an official warning or early-warning system. Data arrive with a delay and
> may be revised. Follow AFAD and Kandilli Observatory for official information.*

---

## Türkçe

### Neler yapar?

- **Dört kaynak, tek istemci:** AFAD olay servisi, Kandilli Rasathanesi (KOERI) son
  depremler listesi, USGS ve EMSC (SeismicPortal) FDSN servisleri aynı anda sorgulanır.
- **Ortak kayıt:** Her deprem bir `Earthquake` nesnesidir: UTC ve TSİ zamanı, enlem,
  boylam, derinlik, büyüklük ve türü (ML, Mw, MD, mb), Türkçe yer adı, il/ilçe, kaynak,
  olay kimliği ve bağlantısı.
- **Tekrarları birleştirme:** Aynı deprem farklı kaynaklarda ±60 sn ve ±30 km içinde
  ise tek kayıt kalır (varsayılan tercih: AFAD > Kandilli > EMSC > USGS); diğerleri
  `also_reported_by` alanında listelenir.
- **Filtreler:** zaman aralığı (`2026-11-01`, `7g`, `24s`), büyüklük, derinlik, kutu
  (bbox), bir nokta çevresinde yarıçap ve **il** (her yazımla veya plaka koduyla:
  `"Muğla"`, `"MUGLA"`, `48`).
- **İl bulma:** 81 ilin sadeleştirilmiş sınırları ve ağırlık merkezleri pakete gömülüdür
  (29 KB, Natural Earth, kamu malı). USGS/EMSC depremleri de Türkçe il adıyla gösterilir.
- **İstatistik:** büyüklük sınıflarına göre sayılar, Gutenberg-Richter **b-değeri**
  (Aki en çok olabilirlik), tamamlılık büyüklüğü **Mc** (maksimum eğrilik).
- **Çıktılar:** Python nesneleri, GeoJSON, JSON, CSV, pandas DataFrame (isteğe bağlı).
- **Komut satırı:** `tr-deprem son | ara | izle`.
- **Bağımlılık yok:** yalnızca Python standart kütüphanesi; zaman aşımı, yeniden deneme
  ve geri çekilme (backoff) her istekte vardır.

### Kurulum

```bash
pip install tr-deprem

# pandas DataFrame çıktısı için
pip install "tr-deprem[pandas]"
```

Python 3.9 ve üzeri gerekir.

### Hızlı başlangıç

```python
import tr_deprem

# Son 24 saat, AFAD + Kandilli, tekrarlar birleştirilmiş, en yeni önce
for d in tr_deprem.son(min_magnitude=3):
    print(d.time_tr, d.magnitude, d.magnitude_type, d.location, d.source)

# Ayrıntılı arama: dört kaynak, Malatya, son 7 gün, M >= 2.5
istemci = tr_deprem.DepremClient("tumu")
depremler = istemci.ara("7g", il="Malatya", min_magnitude=2.5)
print(istemci.errors)          # erişilemeyen kaynak varsa burada görünür

# Bir noktanın çevresi (enlem, boylam) ve yarıçap (km)
yakin = istemci.ara("2026-11-01", center=(38.35, 38.31), radius_km=50)

# İstatistik
gr = tr_deprem.b_value(depremler)             # Mc otomatik; az veri varsa ValueError
print(gr)                                     # örn. "b = 1.02 ± 0.05, a = 4.31, Mc = 2.5, N = 61"
print(tr_deprem.magnitude_bins(depremler))    # örn. {2.0: 48, 3.0: 12, 4.0: 1}

# İl bulma
print(tr_deprem.nearest_il(39.52, 28.92))     # Balıkesir
print(depremler[0].konum())                   # örn. ('Malatya', 'Battalgazi', None)

# Çıktılar
geojson = tr_deprem.to_geojson(depremler)
with open("depremler.csv", "w", encoding="utf-8-sig", newline="") as f:   # Excel için BOM
    tr_deprem.to_csv(depremler, f)
df = tr_deprem.to_dataframe(depremler)        # pip install "tr-deprem[pandas]"
```

### Komut satırı

```console
$ tr-deprem son -n 6
Tarih / Saat (TSİ)   Büy.  Tip  Der.km    Enlem   Boylam  Yer                     Kaynak
-------------------  ----  ---  ------  -------  -------  ----------------------  --------
2026-11-08 22:42:04   1.7  ML      6.7  38.3320  38.8005  CANAKCI-KALE (MALATYA)  Kandilli
2026-11-08 22:23:02   3.3  ML      7.0  39.5192  28.9182  Dursunbey (Balıkesir)   AFAD +1
2026-11-08 22:14:46   1.2  ML      7.0  39.0905  33.1950  Kulu (Konya)            AFAD
2026-11-08 21:51:34   1.5  ML      7.0  37.2708  28.5025  Menteşe (Muğla)         AFAD +1
2026-11-08 21:29:26   1.0  ML      6.6  39.1462  28.2457  Sındırgı (Balıkesir)    AFAD
2026-11-08 21:15:06   2.0  ML     11.1  38.2143  38.5225  Battalgazi (Malatya)    AFAD +1
```

`AFAD +1`: aynı deprem bir başka kaynakta da var (birleştirildi). `--ayri` ile
birleştirmeden gösterilir.

```console
$ tr-deprem son -k tumu -m 3 --saat 72 -n 5
Tarih / Saat (TSİ)   Büy.  Tip  Der.km    Enlem   Boylam  Yer                    Kaynak
-------------------  ----  ---  ------  -------  -------  ---------------------  -------
2026-11-08 22:23:02   3.3  ML      7.0  39.5192  28.9182  Dursunbey (Balıkesir)  AFAD +2
2026-11-08 19:49:19   3.2  ML      7.8  37.8925  35.2612  Yahyalı (Kayseri)      AFAD +2
2026-11-08 14:01:20   3.2  ML      7.0  37.6422  35.3672  Aladağ (Adana)         AFAD +2
2026-11-07 13:42:52   3.3  ML     10.8  40.5937  42.0227  Oltu (Erzurum)         AFAD +2
2026-11-07 02:45:21   3.4  ML      6.9  34.5025  25.0347  Akdeniz                AFAD

$ tr-deprem ara -k afad -b 10g --il Balıkesir --istatistik
Deprem sayısı: 82
Kaynaklara göre: AFAD: 82
Büyüklük aralığı: 0.8 - 3.3
Derinlik aralığı: 5.3 - 15.6 km
Büyüklük dağılımı:
   0.0- 0.9       7  ###
   1.0- 1.9      73  ##############################
   2.0- 2.9       1  #
   3.0- 3.9       1  #
Gutenberg-Richter (Aki MLE): b = 1.51 ± 0.23, Mc = 1.2 (maks. eğrilik), N(M≥Mc) = 54
```

Diğer örnekler:

```bash
tr-deprem ara -b 2026-11-01 -e "2026-11-05 12:00" -m 4 --json      # saatler TSİ
tr-deprem ara -k tumu -b 7g --merkez Malatya --yaricap 100 --csv > malatya.csv
tr-deprem ara -k usgs,emsc -b 30g --bbox 26,36,30,40 --geojson > ege.geojson
tr-deprem izle -m 3 --aralik 60          # her 60 sn'de yeni M≥3 depremleri yazar; Ctrl-C ile durur
tr-deprem izle -k tumu --il İzmir --json # satır başına bir JSON kaydı
```

| Komut | Açıklama | Önemli seçenekler |
|---|---|---|
| `son` | Son depremler (tablo) | `--saat 24`, `-n 20`, `-m`, `--il`, `-k` |
| `ara` | Arama | `-b/-e` (TSİ), `-m/--max-mag`, `--bbox`, `--merkez` + `--yaricap`, `--il`, `--min/max-derinlik`, `--istatistik` |
| `izle` | Yeni depremleri yazdır | `--aralik 60`, `-m`, `--il`, `--ilk`, `--en-fazla` |

Ortak seçenekler: `-k/--kaynak afad,kandilli,usgs,emsc|tumu` (varsayılan `afad,kandilli`),
`--json | --csv | --geojson`, `--ayri`, `--zaman-asimi 15`.

---

## English

### What it does

`tr-deprem` is a dependency-free Python client for earthquakes in and around Türkiye.

- Queries **AFAD**, **Kandilli Observatory (KOERI)**, **USGS** and **EMSC** concurrently
  and returns one list of `Earthquake` dataclasses (UTC + Türkiye time, lat, lon,
  depth, magnitude + type, Turkish location text, province/district, source, id, URL).
- **De-duplicates** the same event across sources (±60 s, ±30 km), keeping the preferred
  source (AFAD > Kandilli > EMSC > USGS by default) and recording the others.
- **Filters** by time, magnitude, depth, bounding box, radius around a point and
  province (`il`, any spelling or plate code).
- **Province lookup** for any epicentre using a bundled 29 KB table of the 81 provinces
  (centroids and ~500 m simplified outlines from public-domain Natural Earth).
- **Statistics**: counts per magnitude bin, Gutenberg-Richter b-value (Aki 1965 maximum
  likelihood with Utsu's binning correction, Shi & Bolt 1982 error) and magnitude of
  completeness by maximum curvature (Wiemer & Wyss 2000).
- **Outputs**: dataclasses, GeoJSON, JSON, CSV, pandas DataFrame (optional extra).
- **CLI** `tr-deprem` with Turkish commands and English aliases (`latest`, `search`, `watch`).

### Install

```bash
pip install tr-deprem
pip install "tr-deprem[pandas]"   # DataFrame output
```

### Quickstart

```python
from tr_deprem import DepremClient, b_value, to_geojson

client = DepremClient(["afad", "kandilli", "usgs", "emsc"], timeout=10, retries=2)

latest = client.latest(hours=6, min_magnitude=2)             # newest first
week = client.search("7d", il="Malatya")                       # province filter
box = client.search("2026-11-01", "2026-11-08", bbox=(26, 36, 30, 40), min_magnitude=3)
near = client.search("30d", center=(38.35, 38.31), radius_km=50)

for eq in latest:
    print(eq.time.isoformat(), eq.time_tr.strftime("%H:%M"), eq.magnitude,
          eq.location_tr, eq.source, eq.also_reported_by)

print(client.errors)        # {"kandilli": "..."} if a source was unreachable
print(b_value(week))        # b = ..., a = ..., Mc = ..., N = ...
geojson = to_geojson(week)

for eq in client.watch(interval=60, min_magnitude=3):          # generator; Ctrl-C to stop
    print("new:", eq.magnitude, eq.location_tr)
```

Times you pass in Python may be `datetime`, `date`, ISO strings or durations such as
`"24h"`, `"7d"`, `"30min"`; **naive values are UTC** in the Python API and **Türkiye time**
in the CLI.

### Command line

```bash
tr-deprem latest -n 10                       # same as "son"
tr-deprem search --start 7d --province Izmir --min-mag 2 --json
tr-deprem search --source all --center 38.35,38.31 --radius 50 --stats
tr-deprem watch --min-mag 4 --interval 30
```

---

## Data sources / Veri kaynakları

| Source | Endpoint | Format | Time zone | Notes |
|---|---|---|---|---|
| AFAD | `https://deprem.afad.gov.tr/apiv2/event/filter` | JSON (numbers as strings) | UTC | Supports time, magnitude, depth, bbox, radius filters. In November 2026 the public API returned only about the **last 10-11 days** of events (older ranges come back empty); use USGS/EMSC for history. |
| Kandilli (KOERI RETMC) | `http://www.koeri.boun.edu.tr/scripts/lst0.asp` | fixed-width text in HTML, windows-1254 | **Türkiye local time** | Only the latest 500 events; no query API, all filters local. Preferred magnitude Mw > ML > MD. |
| USGS | `https://earthquake.usgs.gov/fdsnws/event/1/query` | GeoJSON | UTC (epoch ms) | Global; Türkiye box used when no spatial filter is given. |
| EMSC | `https://www.seismicportal.eu/fdsnws/event/1/query` | GeoJSON | UTC | Global; same default box. |

All four endpoints and their formats were checked against the live services on
2026-11-08. The parsers match fields by name (with fallbacks) and Kandilli lines by
pattern rather than column offsets, accept UTF-8 or windows-1254, and skip malformed
records instead of failing. The FDSN parser also understands the pipe-separated
`format=text` reply.

**Attribution / Atıf.** When you publish data obtained with this package, credit the
original source:

- **AFAD** - T.C. İçişleri Bakanlığı Afet ve Acil Durum Yönetimi Başkanlığı, Deprem Dairesi.
- **Kandilli** - Boğaziçi Üniversitesi Kandilli Rasathanesi ve Deprem Araştırma Enstitüsü,
  Bölgesel Deprem-Tsunami İzleme ve Değerlendirme Merkezi. Their site states that the
  data may be used **with attribution** and **not for commercial purposes** without the
  university's written permission.
- **USGS** - U.S. Geological Survey Earthquake Hazards Program (public domain).
- **EMSC** - European-Mediterranean Seismological Centre, SeismicPortal; follow EMSC's
  terms of use and acknowledge EMSC.
- **Province outlines** - derived from [Natural Earth](https://www.naturalearthdata.com/)
  (public domain) by [`tools/build_iller.py`](tools/build_iller.py).

The library identifies itself with the generic User-Agent `tr-deprem/<version>`, uses
timeouts and limited retries with backoff, and does not poll faster than you ask. Please
keep polling intervals reasonable (the CLI default is 60 s).

### Accuracy notes

- **Province lookup** uses outlines simplified to ~500 m. On 808 onshore AFAD events
  (late Oct - early Nov 2026) it agreed with AFAD's own province label for 91 % of
  them; differences cluster near borders and where AFAD names the nearest settlement's
  province. When a source names the province (AFAD, Kandilli), that name is used.
- **De-duplication** uses fixed tolerances (±60 s, ±30 km by default, both adjustable).
  Different networks can place the same small event more than 30 km apart, and two
  real events close in time and space from different sources may be merged.
- **b-values** from short or small catalogues are unstable; check `n` and `b_error`.

## Development / Geliştirme

```bash
git clone https://github.com/YusufEminoglu/tr_deprem_sdk
cd tr_deprem_sdk
pip install -e ".[dev,pandas]"
python -m pytest --cov=tr_deprem       # tests use saved fixtures, no network
python -m ruff check . && python -m ruff format --check src tests tools
python -m mypy src
```

## Citation

See [`CITATION.cff`](CITATION.cff).

## License

MIT © Yusuf Eminoğlu. Data remain subject to their providers' terms (see above).
