예제 #1
0
def test_check_ccode():
    for ccode in ["AFG", "CHN", "USA", "FRA"]:
        assert check_ccode(ccode)

    try:
        assert check_ccode("foo")
    except Exception:
        pass
예제 #2
0
def test_check_ccode():
    for ccode in ['AFG', 'CHN', 'USA', 'FRA']:
        assert check_ccode(ccode)

    try:
        assert check_ccode('foo')
    except Exception:
        pass
예제 #3
0
def main():
    parser = get_parser()
    args = parser.parse_args()

    # make sure we don't have -e option AND --numdays option
    if args.endTime is not None and args.numdays is not None:
        msg = ('You must specify end time or number of days since '
               'start time, not both. Exiting.')
        print(msg)
        sys.exit(1)

    if not args.endTime and args.numdays:
        args.endTime = args.startTime + timedelta(args.numdays)

    setup_logger(args.logfile, args.loglevel)

    tsum = (args.bounds is not None) + \
        (args.radius is not None) + (args.country is not None)
    if tsum != 1:
        logging.error(
            'Please specify a bounding box, radius, or country code.')
        sys.exit(1)

    latitude = None
    longitude = None
    radiuskm = None
    lonmin = latmin = lonmax = latmax = None
    bounds = None
    if args.radius:
        latitude = args.radius[0]
        longitude = args.radius[1]
        radiuskm = args.radius[2]

    if args.bounds:
        lonmin, lonmax, latmin, latmax = args.bounds
        # fix longitude bounds when crossing dateline
        if lonmin > lonmax and lonmax >= -180:
            lonmin -= 360
    else:
        lonmin, lonmax, latmin, latmax = None, None, None, None
        bounds = (lonmin, lonmax, latmin, latmax)

    if args.country:
        ccode = args.country
        if not check_ccode(ccode):
            curl = 'https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2'
            fmt = ('%s is not a valid ISO 3166 country code. '
                   'See %s for the list.')
            tpl = (ccode, curl)
            logging.error(fmt % tpl)
            sys.exit(1)
        bounds = get_country_bounds(ccode, args.buffer)  # this returns a list

    minmag = 0.0
    maxmag = 9.9
    if args.magRange:
        minmag = args.magRange[0]
        maxmag = args.magRange[1]

    minsig = 0
    maxsig = 5000
    if args.sigRange:
        minsig = args.sigRange[0]
        maxsig = args.sigRange[1]

    if args.getCount:
        if isinstance(bounds, tuple) or bounds is None:
            nevents = count(starttime=args.startTime,
                            endtime=args.endTime,
                            updatedafter=args.after,
                            minlatitude=latmin,
                            maxlatitude=latmax,
                            minlongitude=lonmin,
                            maxlongitude=lonmax,
                            latitude=latitude,
                            longitude=longitude,
                            maxradiuskm=radiuskm,
                            catalog=args.catalog,
                            contributor=args.contributor,
                            maxmagnitude=maxmag,
                            minmagnitude=minmag,
                            minsig=minsig,
                            maxsig=maxsig,
                            producttype=args.limitByProductType)
        else:
            for lonmin, lonmax, latmin, latmax in bounds:
                nevents = 0
                nevents += count(starttime=args.startTime,
                                 endtime=args.endTime,
                                 updatedafter=args.after,
                                 minlatitude=latmin,
                                 maxlatitude=latmax,
                                 minlongitude=lonmin,
                                 maxlongitude=lonmax,
                                 latitude=latitude,
                                 longitude=longitude,
                                 maxradiuskm=radiuskm,
                                 catalog=args.catalog,
                                 contributor=args.contributor,
                                 minsig=minsig,
                                 maxsig=maxsig,
                                 maxmagnitude=maxmag,
                                 minmagnitude=minmag,
                                 producttype=args.limitByProductType)
        print('There are %i events matching input criteria.' % nevents)
        sys.exit(0)
    if isinstance(bounds, tuple) or bounds is None:
        events = search(starttime=args.startTime,
                        endtime=args.endTime,
                        updatedafter=args.after,
                        minlatitude=latmin,
                        maxlatitude=latmax,
                        minlongitude=lonmin,
                        maxlongitude=lonmax,
                        latitude=latitude,
                        longitude=longitude,
                        maxradiuskm=radiuskm,
                        catalog=args.catalog,
                        contributor=args.contributor,
                        maxmagnitude=maxmag,
                        minmagnitude=minmag,
                        minsig=minsig,
                        maxsig=maxsig,
                        producttype=args.limitByProductType,
                        host=args.host,
                        eventtype=args.event_type,
                        alertlevel=args.alert_level)
    else:
        events = []
        for i, tbounds in enumerate(bounds):
            lonmin, lonmax, latmin, latmax = tbounds
            fmt = 'Checking bounds %i of %i for %s...\n'
            tpl = (i + 1, len(bounds), ccode)
            logging.debug(fmt % tpl)
            tevents = search(starttime=args.startTime,
                             endtime=args.endTime,
                             updatedafter=args.after,
                             minlatitude=latmin,
                             maxlatitude=latmax,
                             minlongitude=lonmin,
                             maxlongitude=lonmax,
                             latitude=latitude,
                             longitude=longitude,
                             maxradiuskm=radiuskm,
                             catalog=args.catalog,
                             contributor=args.contributor,
                             maxmagnitude=maxmag,
                             minmagnitude=minmag,
                             minsig=minsig,
                             maxsig=maxsig,
                             producttype=args.limitByProductType,
                             host=args.host,
                             eventtype=args.event_type,
                             alertlevel=args.alert_level)
            events += tevents

    if not len(events):
        logging.info('No events found matching your search criteria. Exiting.')
        sys.exit(0)

    if (args.getAngles != 'none' or
            args.getAllMags or
            args.getComponents != 'none'):

        logging.info(
            'Fetched %i events...creating table.\n' % (len(events)))
        supp = args.getMomentSupplement
        df = get_detail_data_frame(events, get_all_magnitudes=args.getAllMags,
                                   get_tensors=args.getComponents,
                                   get_focals=args.getAngles,
                                   get_moment_supplement=supp)
    else:
        logging.info(
            'Fetched %i events...creating summary table.\n' % (len(events)))
        df = get_summary_data_frame(events)

    # order the columns so that at least the initial parameters come the way
    # we want them...
    first_columns = list(events[0].toDict().keys())
    col_list = list(df.columns)
    for column in first_columns:
        try:
            col_list.remove(column)
        except Exception as e:
            x = 1
    df = df[first_columns + col_list]

    if args.country:
        df = filter_by_country(df, ccode, buffer_km=args.buffer)

    logging.info('Created table...saving %i records to %s.\n' %
                 (len(df), args.filename))
    if args.format == 'excel':
        df.to_excel(args.filename, index=False)
    elif args.format == 'tab':
        df.to_csv(args.filename, sep='\t', index=False)
    else:
        df.to_csv(args.filename, index=False, chunksize=1000)
    logging.info('%i records saved to %s.' % (len(df), args.filename))
    sys.exit(0)
예제 #4
0
def main():
    parser = get_parser()
    args = parser.parse_args()

    # --host and --scenario are mutually exclusive
    if args.host is not None and args.scenario:
        print(
            '--host and --scenario options are mutually exclusive. Please choose one.'
        )
        sys.exit(1)

    setup_logger(args.logfile, args.loglevel)

    if args.eventid:
        detail = get_event_by_id(args.eventid,
                                 includesuperseded=True,
                                 scenario=args.scenario)
        _get_product_from_detail(detail,
                                 args.product,
                                 args.contents,
                                 args.outputFolder,
                                 args.version,
                                 args.source,
                                 list_only=args.list_only)
        sys.exit(0)

    tsum = (args.bounds is not None) + \
        (args.radius is not None) + (args.country is not None)
    if tsum != 1:
        print('Please specify a bounding box, radius, or country code.')
        sys.exit(1)

    latitude = None
    longitude = None
    radiuskm = None
    lonmin = latmin = lonmax = latmax = None

    if args.startTime is None:
        starttime = datetime.utcnow() - timedelta(days=30)
        print('You did not specify a search start time, defaulting to %s' %
              str(starttime))
    else:
        starttime = args.startTime

    if args.endTime is None:
        endtime = datetime.utcnow()
        print('You did not specify a search end time, defaulting to %s' %
              str(endtime))
    else:
        endtime = args.endTime

    bounds = None
    if args.radius:
        latitude = args.radius[0]
        longitude = args.radius[1]
        radiuskm = args.radius[2]

    if args.bounds:
        lonmin, lonmax, latmin, latmax = args.bounds
        # fix longitude bounds when crossing dateline
        if lonmin > lonmax and lonmax >= -180:
            lonmin -= 360
    else:
        lonmin, lonmax, latmin, latmax = None, None, None, None
        bounds = (lonmin, lonmax, latmin, latmax)

    if args.country:
        ccode = args.country
        if not check_ccode(ccode):
            curl = 'https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2'
            fmt = '%s is not a valid ISO 3166 country code. See %s for the list.'
            tpl = (ccode, curl)
            print(fmt % tpl)
            sys.exit(1)
        bounds = get_country_bounds(ccode, args.buffer)  # this returns a list

    minmag = 0.0
    maxmag = 9.9
    if args.magRange:
        minmag = args.magRange[0]
        maxmag = args.magRange[1]

    if isinstance(bounds, tuple) or bounds is None:
        events = search(starttime=starttime,
                        endtime=endtime,
                        updatedafter=args.after,
                        minlatitude=latmin,
                        maxlatitude=latmax,
                        minlongitude=lonmin,
                        maxlongitude=lonmax,
                        latitude=latitude,
                        longitude=longitude,
                        maxradiuskm=radiuskm,
                        catalog=args.catalog,
                        contributor=args.contributor,
                        producttype=args.product,
                        eventtype=args.eventType,
                        maxmagnitude=maxmag,
                        minmagnitude=minmag,
                        scenario=args.scenario,
                        host=args.host)
    else:
        events = []
        for i, tbounds in enumerate(bounds):
            lonmin, lonmax, latmin, latmax = tbounds
            tevents = search(starttime=starttime,
                             endtime=endtime,
                             updatedafter=args.after,
                             minlatitude=latmin,
                             maxlatitude=latmax,
                             minlongitude=lonmin,
                             maxlongitude=lonmax,
                             latitude=latitude,
                             longitude=longitude,
                             maxradiuskm=radiuskm,
                             catalog=args.catalog,
                             contributor=args.contributor,
                             producttype=args.product,
                             eventtype=args.eventType,
                             maxmagnitude=maxmag,
                             minmagnitude=minmag,
                             scenario=args.scenario,
                             host=args.host)
            events += tevents

    if not len(events):
        print('No events found matching your search criteria. Exiting.')
        sys.exit(0)

    if args.country:
        ids = [event.id for event in events]
        lats = [event.latitude for event in events]
        lons = [event.longitude for event in events]
        df = pd.DataFrame({'id': ids, 'latitude': lats, 'longitude': lons})
        df2 = filter_by_country(df, ccode, buffer_km=args.buffer)
        events = [event for event in events if event.id in df2['id'].unique()]

    for event in events:
        logging.debug('Retrieving products for event %s...' % event.id)
        if not event.hasProduct(args.product):
            continue
        try:
            detail = event.getDetailEvent(includesuperseded=True,
                                          scenario=args.scenario)
        except Exception as e:
            print(
                'Failed to retrieve detail event for event %s... continuing.' %
                event.id)
            continue
        _get_product_from_detail(detail,
                                 args.product,
                                 args.contents,
                                 args.outputFolder,
                                 args.version,
                                 args.source,
                                 list_only=args.list_only)

    sys.exit(0)