readbol.py 21.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
#!/usr/bin/python
# coding: utf-8
#
##
#
# Program to parse, plot, dump the boletim files that are maintained by USP.
# Completude curves are the one presented by Bianchi et. al. 2018 (SRL).
# Brazil polygon curve is the one that we use everywhere.
# 
# Also, this program documents most of the fields in those files and its
# meaning.
#
# M. Bianchi @ 2020
#
##

from __future__ import print_function, division

from optparse import OptionParser
import datetime, os

import sys, warnings

import numpy as np

from mpl_toolkits.basemap import Basemap
from matplotlib import pyplot as plt

from obspy.core import AttribDict, UTCDateTime

#
## Supress warnings
#

warnings.simplefilter("ignore")

#
## Utils
#

def log(msg, doquit = False):
    '''
    Log stuff
    '''
    print(msg, file = sys.stderr)
    if doquit: sys.exit(1)


def number(val, default = None, fixtype = None):
    '''
    Try to get a number out of the mess
    '''
    try:
        val = float(val.replace("--", " ").replace("- ", "").replace(" ", "").strip())
        
        if fixtype is not None:
            val = fixtype(val)
    except:
        val = default
    
    return val

#
## Filters
#

def inpolygon(evento, poly = None):
    '''
    Check that event is inside poly
    '''
    if poly is None:
        poly = [(-45.,6.),(-68.,6.),
                (-75.,-7.),(-73.5,-10.),
                (-69.,-12.),(-67.,-12.),
                (-62.,-16.),(-62.,-34.),
                (-45.,-34.),(-33.,-20.),
                (-33.,-5.),(-45.,6.)]
    
    x = evento.longitude
    y = evento.latitude
    
    n = len(poly)
    
    inside = False
    
    p1x,p1y = poly[0]
    for i in range(n+1):
        p2x,p2y = poly[i % n]
        if y > min(p1y,p2y):
            if y <= max(p1y,p2y):
                if x <= max(p1x,p2x):
                    if p1y != p2y:
                        xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
                    if p1x == p2x or x <= xints:
                        inside = not inside
        p1x,p1y = p2x,p2y
    return inside


def completudeOne(evento):
    '''
    Filter earthquakes to make catalog as complete as we think
    '''
    global years, years2
    
    if evento.magnitude is None: return False
    
    limit_mag = np.interp(evento.ot, years[0], years[1])
    return evento.magnitude >= limit_mag


def completudeTwo(evento):
    '''
    Filter earthquakes to make catalog as complete as we think
    '''
    global years, years2
    
    if evento.magnitude is None: return False
    if evento.ot < years2[0][0]: return False
    limit_mag = np.interp(evento.ot, years2[0], years2[1])
    return evento.magnitude >= limit_mag


def makeregion(region):
    '''
    Returns a function that can filter events
    form a region to be used by python filter
    '''
    lona, lonb, lata, latb = region.split("/")
    
    try: lona = float(lona)
    except: lona = -180.
    
    try: lonb = float(lonb)
    except: lonb = 180.
    
    try: lata = float(lata)
    except: lata = -90.
    
    try: latb = float(latb)
    except: latb = 90.
    
    return lambda e: e.longitude >= lona and e.longitude <= lonb and e.latitude >= lata and e.latitude <= latb

#
## Class
#

# ~ SRL Completude curves models.
years = [ [UTCDateTime('1940-01-01'),
           UTCDateTime('1962-01-01'),UTCDateTime('1962-01-01'),
           UTCDateTime('1968-01-01'),UTCDateTime('1968-01-01'),
           UTCDateTime('2014-01-01'),UTCDateTime('2014-01-01'),
           UTCDateTime()],
          [6.0,
           6.0,5.0,
           5.0,4.5,
           4.5,3.5,
           3.5]]

years2 = [ [UTCDateTime('1940-01-01'),
            UTCDateTime('1962-01-01'),UTCDateTime('1962-01-01'),
            UTCDateTime('1968-01-01'),UTCDateTime('1968-01-01'),
            UTCDateTime('1980-01-01'),UTCDateTime('1980-01-01'),
            UTCDateTime()],
          [6.0,
           6.0,5.0,
           5.0,4.5,
           4.5,3.5,
           3.5]]


class Evento(object):
    '''
    Holder class of information, also able to parse line by fixed column positions
    '''
    def __init__(self, line):
        self._ot         = None
        self._latitude   = None
        self._longitude  = None
        self._erh        = None
        self._estado     = None
        self._profundidade = None
        self._magnitude  = None
        self._t          = None
        self._categoria  = None
        self._area       = None
        self._intensidade = None
        self._comentario = None
        
        if line is not None and line != '':
            ano         = line[1:5]
            mesdia      = line[6:10]
            hms         = line[11:19]
            
            # Fields
            if not self.setOt(ano, mesdia, hms):
                raise Exception("Date is invalid -- {} {} {}".format(ano, mesdia, hms))

            if not self.setLatitude(line[19:25]):
                raise Exception("Latitude is invalid -- {}".format(line[19:25]))
            
            if not self.setLongitude(line[25:32]):
                raise Exception("Longitude is invalid -- {}".format(line[25:32]))
            
            if not self.setErh(line[33:36]):
                raise Exception("Erh is invalid -- {}".format(line[33:36]))
            
            if not self.setEstado(line[37:39]):
                raise Exception("Estado is invalid -- {}".format(line[37:39]))
            
            if not self.setProfundidade(line[40:44]):
                raise Exception("Profundidade is invalid -- {}".format(line[40:44]))
            
            if not self.setMagnitude(line[45:49]):
                raise Exception("Magnitude is invalid -- '{}'".format(line[45:49]))
            
            if not self.setT(line[51:52]):
                raise Exception("T is invalid -- {}".format(line[51:52]))
            
            if not self.setCategoria(line[54:55]):
                raise Exception("Categoria is invalid -- {}".format(line[54:55]))
            
            if not self.setIntensidade(line[56:59]):
                raise Exception("Intensidade is invalid -- {}".format(line[56:59]))
            
            if not self.setArea(line[60:65]):
                raise Exception("Area is invalid -- {}".format(line[60:65]))
            
            if len(line) > 66:
                self._comentario = line[66:].strip()

    #
    ## Set & Getters
    #
    @property
    def ot(self):
        return self._date

    def setOt(self, ano, mesdia, hms):
        pano = None
        pmes = 6
        pdia = 15
        pH   = 12
        pM   = 30
        pS   = 30
        
        # Ano
        try:
            if len(ano) != 4: return None
            pano = number(ano, None, int)
            if pano is None: raise ValueError()
        except ValueError:
            log("Wow: Cannot parse ANO -- {} {} {}".format(ano,mesdia,hms))
            return False
        
        # Mes / Dia
        mesdia = mesdia.replace(" ", "").replace("-","").strip()
        if len(mesdia) == 3:
            log("Wow: Cannot parse MES DIA -- {} {} {}".format(ano,mesdia,hms))
            return False
        
        if len(mesdia) == 4:
            pmes = number(mesdia[:2], pmes, int)
            pdia = number(mesdia[2:], pdia, int)
        elif len(mesdia) >= 1:
            pmes = number(mesdia, pmes, int)
        
        # Hora / Minuto / Segundo
        hms = hms.replace(" ", "").replace("-","").strip()
        if len(hms) > 4:
            pH = number(hms[0:2], pH, int)
            pM = number(hms[2:4], pM, int)
            pS = number(hms[4:], pS, float)
        elif len(hms) > 2:
            pH = int(hms[0:2])
            pM = int(hms[2:4])
        elif len(hms) > 0:
            pH = int(hms[0:2])
        
        self._date = UTCDateTime(pano, pmes, pdia, pH, pM, pS)
        
        return True

    @property
    def latitude(self):
        return self._latitude if self._latitude is not None else -90.
    
    def setLatitude(self, val):
        val = number(val, None)
        
        if val is not None and (val < -90 or val > 90):
            return False
        
        self._latitude = val
        
        return True

    @property
    def longitude(self):
        return self._longitude if self._longitude is not None else -180.
    
    def setLongitude(self, val):
        val = number(val, None)
        if val is not None and (val < -180 or val > 180):
            return False
        self._longitude = val
        return True

    @property
    def erh(self):
        return self._erh
    
    def setErh(self, val):
        self._erh = number(val, -1.)
        return True

    @property
    def estado(self):
        return self._estado
    
    def setEstado(self, val, como_nome = False):
        val = val.strip()
        val = val.upper()
        
        if len(val) > 2: return False
        
        valid = {
                # Brazilian States
                "AC" : "Acre",
                "AL" : "Alagoas",
                "AP" : "Amapá",
                "AM" : "Amazonas",
                "BA" : "Bahia",
                "CE" : "Ceará",
                "DF" : "Distrito Federal",
                "ES" : "Espírito Santo",
                "GO" : "Goiás",
                "MA" : "Maranhão",
                "MT" : "Mato Grosso",
                "MS" : "Mato Grosso do Sul",
                "MG" : "Minas Gerais",
                "PA" : "Pará",
                "PB" : "Paraíba",
                "PR" : "Paraná",
                "PE" : "Pernambuco",
                "PI" : "Piauí",
                "RJ": "Rio de Janeiro",
                "RN" : "Rio Grande do Norte",
                "RS" : "Rio Grande do Sul",
                "RO" : "Rondônia",
                "RR" : "Roraima",
                "SC" : "Santa Catarina",
                "SP" : "São Paulo",
                "SE" : "Sergipe",
                "TO" : "Tocantins",
                # Countries
                "BO" : "Bolivia",
                "BR" : "Brazil",
                "PY" : "Paraguay",
                "AR" : "Argentina",
                "UY" : "Urugay",
                "GY" : "Guyana",
                "GA" : "Guyana Francesa",
                "CH" : "Chile",
                "PU" : "Peru",
                # Garbage in there
                "-"  : "None",
                "E"  : "None"
        }
        
        if val not in valid: return False
        
        self._estado = val if como_nome == False else valid[val]
        
        return True
    
    @property
    def profundidade(self):
        return self._profundidade if self._profundidade is not None else -9.9
    
    def setProfundidade(self, val):
        val = number(val, None)
        
        if val is not None and (val < -5 and val > 1000.):
            return False
        
        self._profundidade = val
        
        return True
    
    @property
    def magnitude(self):
        return self._magnitude if self._magnitude is not None else -9.9
    
    def setMagnitude(self, val):
        val = number(val, None)
        
        if val is not None and (val < -4 or val > 9.6):
            return False
        
        self._magnitude = val
        
        return True

    @property
    def categoria(self):
        return self._categoria
    
    def setCategoria(self, val, como_nome = False):
        val = val.replace("-", "").strip()
        
        valid = {
            'U' : 'Unknow',
            
            'I' : 'dado instrumental',
            'A' : 'dados macrossísmicos detalhados para determinar o epicentro e isossistas',
            'B' : 'dados macrossísmicos suficientes para estimar epicentro e a área afetada total',
            'C' : 'dados macrossísmicos insuficientes para estimar área afetada',
            'D' : 'dado duvidoso: dado equivocado, suspeita de erro, ou não é sismo natural',
            'E' : 'terremoto forte fora do Brasil, mas que foi sentido em uma ou mais cidades do país'
        }

        if val not in valid.keys():
            return False
        
        self._categoria = val if como_nome is False else valid[val]
        
        return True

    @property
    def t(self):
        return self._t
    
    def setT(self, val):
        val = number(val, -1, int)

        valid = {
            -1 : 'magnitude não disponível (valor=0.0 significando que não há dados)',
             0 : 'magnitude de onda P com estações a distâncias telessísmicas (mb IASPEI)',
             1 : 'magnitude mR com estações regionais (Assumpção, 1983)',
             2 : 'média de mb e mR',
             3 : 'magnitude estimada pela área afetada (Berrocal et al., 1984): `mag = 1.63  +  0.60 log (Area II, km2)` ou `mag = 2.29  +  0.55 log (Area IV, km2)`',
             4 : 'magnitude estimada com Intensidade máxima Io (sem Área afetada disponível): `mag = 1.21  +  0.45 Io`',
             5 : 'magnitude estimada indiretamente'
        }
        
        if val not in valid:
            return False
        
        self._t = val
        
        return True

    @property
    def area(self):
        '''
        Area afetada em km^3
        '''
        return self._area if self._area is not None else -1
    
    def setArea(self, val):
        self._area = number(val, None)
        return True

    @property
    def intensidade(self):
        return self._intensidade
    
    def setIntensidade(self, val):
        ma = mb = None
        val = val.strip()
        
        if val == '':
            self._intensidade = None
            return True
        
        if val.count("-") == 0:
            ma = mb = number(val, -1, int)
        elif val.count("-") == 1:
            a,b = val.split("-")
            ma = number(a.strip(), ma, int)
            mb = number(b.strip(), mb, int)
        else:
            try:
                val = number(val)
                if val is None: raise Exception("")
                ma = mb = val
            except:
                self._intensidade = None
                return False
        
        if ma is None or mb is None: 
            self._intensidade = None
            return True
        
        self._intensidade = (ma, mb)
        
        return True

    @property
    def comentario(self):
        return self._comentario

    #
    ## Utils
    #
    def asDict(self):
        return AttribDict({
            'ot'           : self.ot,
            'latitude'     : self.latitude,
            'longitude'    : self.longitude,
            'err'          : self.err,
            'estado'       : self.estado,
            'profundidade' : self.profundidade,
            'magnitude'    : self.magnitude,
            't'            : self.t,
            'cat'          : self.categoria,
            'io'           : self.intensidade,
            'area'         : self.area,
            'comentario'   : self.comentario
        })
    
    @staticmethod
    def headers():
        return "Ot;Latitude;Longitude;Erh;Profundidade;Magnitude;Estado;Tipo M.;Categoria;Intensidade;Area;Commentario"
        
    def __str__(self):
        return "{};{:6.2f};{:7.2f};{:3.0f};{:5.1f};{:4.1f};{:2s};{:2d};{};{:3s};{:5.1f};{}".format(
            self.ot.strftime("%Y-%m-%dT%H:%M:%S"),
            self.latitude,
            self.longitude,
            self.erh,
            self.profundidade,
            self.magnitude,
            self.estado,
            self.t,
            self.categoria,
            (("{}-{}".format(*self.intensidade)) if self.intensidade[0] != self.intensidade[1] else " {} ".format(self.intensidade[0])) if self.intensidade is not None else " - ",
            self.area,
            self.comentario.replace(";",",")
        )


def readbol(filename):
    '''
    Read w/ iterator
    '''
    def domagic(filename):
        try:
            import magic
            m = magic.open(magic.MAGIC_MIME_ENCODING)
            m.load()
            code = m.file(filename)
        except:
            log(" -> No python3-magic found, I can guess wrong the file encoding, please use python2 or, install python3-magic\n")
            return 'utf-8'
        
        if code[:8] == 'iso-8859':
            log(" -> File '{}' is ISO, please upgrade!!!\n".format(filename))
        
        return code

    if sys.version_info.major >=3:
        with open(filename, "r", encoding = domagic(filename)) as fio:
            for line in fio:
                if line.strip() == "": continue
                if len(line.strip()) < 20: continue
                
                if "YEAR" in line: continue
                if "ANO" in line: continue
                
                yield Evento(line)
    else:
        with open(filename, "r") as fio:
            for line in fio:
                if line.strip() == "": continue
                if len(line.strip()) < 20: continue
                
                if "YEAR" in line: continue
                if "ANO" in line: continue
                
                yield Evento(line)
        
    return


#
## Operations
#

def plot_map(bol):
    '''
    Plot boletim
    '''
    M = Basemap(projection='ortho', lon_0=-45, lat_0 = -25, resolution='c')
    
    M.fillcontinents(color='coral',lake_color='aqua')
    M.drawmapboundary(fill_color='aqua')
    M.drawcoastlines()
    M.drawcountries()
    
    M.etopo()
        
    lon = [ e.longitude for e in bol ]
    lat = [ e.latitude for e in bol ]
    
    lon, lat = M(lon, lat)
    M.scatter(lon, lat, marker='*', color='w', linewidth=0.5, facecolor='k', zorder = 3, label = 'Stations')


def plot_time_evolution(bol):
    '''
    Plot catalog completude
    '''
    years = [ [UTCDateTime('1940-01-01'),UTCDateTime('1962-01-01'),UTCDateTime('1962-01-01'),
               UTCDateTime('1968-01-01'),UTCDateTime('1968-01-01'),UTCDateTime('2014-01-01'),
               UTCDateTime('2014-01-01'),UTCDateTime('2025-01-01')],
              [6.0,6.0,5.0,5.0,4.5,4.5,3.5,3.5]]

    years2 = [ [UTCDateTime('1940-01-01'),UTCDateTime('1962-01-01'),UTCDateTime('1962-01-01'),
               UTCDateTime('1968-01-01'),UTCDateTime('1968-01-01'),UTCDateTime('1980-01-01'),
               UTCDateTime('1980-01-01'),UTCDateTime('2025-01-01')],
              [6.0,6.0,5.0,5.0,4.5,4.5,3.5,3.5]]

    x = np.array([ event.ot.datetime for event in bol ])
    y = np.array([ event.magnitude for event in bol ])

    plt.plot(map(lambda x: x.datetime, years2[0]), years2[1], "--", label = 'SRL 2')
    plt.plot(map(lambda x: x.datetime, years[0]), years[1], label = 'SRL 1')
    plt.scatter(x, y, np.exp(y/2.), edgecolors = 'black', color = 'white')
    plt.legend()
    
    plt.ylim([2.75,6.25])
    plt.xlim([UTCDateTime("1940-01-01").datetime, UTCDateTime("2020-01-01").datetime])
    plt.xlabel('Year')
    plt.ylabel('Magnitude')


def exportgmt(bol):
    '''
    Dump events in a GMT friendly format
    '''
    for e in bol:
        print("{:-8.2f} {:+8.2f} {:5.1f} {:8.1f}".format(e.longitude, e.latitude, e.magnitude, e.profundidade))

#
## Main Code
#

if __name__ == "__main__":
    bolall = []
    
    parser = OptionParser(prog = "readbol.py", usage = "%prog  [-R|--brazil] [--srl1|--srl2] <[-m]|[-d]|[-g]> <FILES>")
    
    parser.add_option("-R",       help = "Region to select data.",     dest = "region",  default = None)
    parser.add_option("--brazil", help = "Filter data by BR polygon.", dest = "brzpoly", action='store_true')

    parser.add_option("--srl1", help = "Make a completude clean up using SRL line #1.", dest = "srlone", action='store_true')
    parser.add_option("--srl2", help = "Make a completude clean up using SRL line #2.", dest = "srltwo", action='store_true')

    parser.add_option("-m", "--map",  help = "Plot a Map & completude curve.", action = "store_true", dest = "domap", default = False)
    parser.add_option("-d", "--dump", help = "Dump the FULL file.", action = "store_true", dest = "dodump", default = False)
    parser.add_option("-g", "--gmt",  help = "Dump the GMT file (x,y,mag,depth).", action = "store_true", dest = "dogmtdump", default = False)
    
    #
    ## Parse Command Line
    #
    (options, args) = parser.parse_args()
    if not args:
        log("No files process.", True)
    
    if options.brzpoly and options.region is not None:
        log("Cannot use --brazil and -R options together.",True)
    
    if options.srlone and options.srltwo:
        log("Options --srl1 and --srl2 are mutually exclusive.", True)
    
    if not options.domap and not options.dodump and not options.dogmtdump:
        log("Will check check that I can read the supplied files and quit, nothing to do!")
    
    #
    ## Read all bulletins
    #
    for filename in args:
        if not os.path.isfile(filename):
            log("File not found: '{}'.".format(filename))
            continue
        log("Reading -- '{}'.".format(filename))
        bolall.extend(readbol(filename))
    
    #
    ## Filter for events in Brazil Polygon
    #
    if options.brzpoly:
        bolall = list(filter(inpolygon, bolall))
    elif options.region is not None:
        inregion = makeregion(options.region)
        bolall = list(filter(inregion, bolall))
    
    #
    ## Filter Complete
    #
    if options.srlone:
        bolall = list(filter(completudeOne, bolall))
    elif options.srltwo:
        bolall = list(filter(completudeTwo, bolall))
    
    #
    ## Plots
    #
    if options.domap:
        plt.subplot(1,2,1)
        plot_time_evolution(bolall)

        plt.subplot(1,2,2)
        plot_map(bolall)
        
        plt.show()
    
    #
    ## Dump
    #
    if options.dodump:
        print(Evento.headers())
        list(map(print, bolall))
    elif options.dogmtdump:
        exportgmt(bolall)
    
    sys.exit(0)