示例#1
0
def validateService(facility, country = None, **kwargs):
    """Generic validation function.

        >>> validate.validateService(country, **kwargs)
    """
    if not isinstance(facility, string_types):
        raise TypeError("Wrong type for input service - must be the facility type")
    elif not facility in FACILITIES.keys():
        raise IOError("Service type not recognised - must be a string in the list '%s'" % list(FACILITIES.keys()))
    if country is None:
        country = list(COUNTRIES.keys())
    if not isinstance(country, string_types) and isinstance(country, Sequence):
        for ctry in country:
            try:
                validateService(country=ctry, **kwargs)
            except:
                continue
        return
    elif not isinstance(country, string_types):
        raise TypeError('wrong type for input country code - must the ISO 2-letter string')
    elif not country in COUNTRIES.keys():
        raise IOError('country code not recognised - must a code of the %s area' % list(COUNTRIES.keys()))
    cfg = FACMETADATA[facility]
    fmt = 'csv'
    src = kwargs.pop('src', None)
    if src is None:
        src = osp.join(cfg.get('path'), fmt, cfg.get('file') % (country, cfg.get('fmt',{})[fmt]))
        logging.warning("\n! Input data file '%s' will be controlled for validation" % src)
    try:
        assert osp.exists(src)
    except:
        raise FileNotFoundError("Input file '%s' not found" % src)
    validate = validateFacilityData
    try:
        validate(facility, src)
    except:
        raise IOError("Data error detected - See warning/error reports")
    else:
        print("! Data passed validation (see warning reports) !")
    return
示例#2
0
def isoCountry(arg):
    """Given a country name or an ISO 3166 code, return the pair {name,code}.

        >>> country = isoCountry(country_or_cc)

    Examples
    --------

        >>> geo.isoCountry('CZ')
            {'code': 'CZ', 'country': 'Czechia'}
        >>> geo.isoCountry('Greece')
            {'code': 'EL', 'country': 'Greece'}
    """
    country, cc = None, None
    if not (arg is None or isinstance(arg, (string_types,Mapping))):
        raise TypeError("Wrong format for country/code '%s' - must be a string or a dictionary" % arg)
    elif isinstance(arg, string_types):
        if arg in COUNTRIES.keys():
            cc, country = arg, None
        elif arg in COUNTRIES.values():
            cc, country = None, arg
        else:
            raise IOError("Country/code '%s' not recognised" % arg)
    elif isinstance(arg, Mapping):
        if 'code' in arg or 'name' in arg:
            cc, country = arg.get('code', None), arg.get('name', None)
        else:
            try:
                cc, country = list(next(iter(arg.items()))) # list(arg.items())[0]
            except:
                pass
    if cc in ('', None) and country in ('', {}, None):
        raise IOError("Missing parameters to define country/code")
    elif cc in ('', None): # and NOT country in ('', {}, None)
        try:
            cc = dict(map(reversed, COUNTRIES.items())).get(country)
        except:
            #cc = country.split()
            #if len(cc) >1:              cc = ''.join([c[0].upper() for c in country.split()])
            #else:                       cc = country # cc[0]
            cc = None
    elif country in ('', {}, None): # and NOT cc in ('', None)
        try:
            country = COUNTRIES.get(cc)
        except:     country = None
    return {'code': cc, 'name': country}
示例#3
0
 ("lat",      {"name": "lat",                    "desc": "Latitude (WGS 84)",
               "type": float.__name__,           "values": None}),
 ("lon",      {"name": "lon",                    "desc": "Longitude (WGS 84)",
               "type": float.__name__,           "values": None}),
 ("geo_qual", {"name": "geo_qual",               "desc": "A quality indicator for the geolocation - 1: Good, 2: Medium, 3: Low, -1: Unknown",
               "type": int.__name__,             "values": [-1, 1, 2, 3]}),
 ("street",   {"name": "street",                 "desc": "Street name",
               "type": str.__name__,             "values": None}),
 ("number",   {"name": "house_number",           "desc": "House number",
               "type": str.__name__,             "values": None}),
 ("postcode", {"name": "postcode",               "desc": "Postcode",
               "type": str.__name__,             "values": None}),
 ("city",     {"name": "city", "desc":           "City name (sometimes refers to a region or a municipality)",
               "type": str.__name__,             "values": None}),
 ("cc",       {"name": "cc", "desc":             "Country code (ISO 3166-1 alpha-2 format)",
               "type": str.__name__,             "values": list(__COUNTRIES.keys())}),
 ("country",  {"name": "country",                "desc": "Country name",
               "type": str.__name__,             "values": None}),
 ("beds",     {"name": "cap_beds",               "desc": "Measure of capacity by number of beds (most common)",
               "type": int.__name__,             "values": None}),
 ("prac",     {"name": "cap_prac",               "desc": "Measure of capacity by number of practitioners",
               "type": int.__name__,             "values": None}),
 ("rooms",    {"name": "cap_rooms",              "desc": "Measure of capacity by number of rooms",
               "type": int.__name__,             "values": None}),
 ("ER",       {"name": "emergency",              "desc": "Flag 'yes/no' for whether the healthcare site provides emergency medical services",
               "type": str.__name__,            "values": ['yes', 'no']}),
 ("type",     {"name": "facility_type",          "desc": "If the healthcare service provides a specific type of care, e.g. psychiatric hospital",
               "type": str.__name__,             "values": None}),
 ("PP",       {"name": "public_private",         "desc": "Status 'private/public' of the healthcare service",
               "type": str.__name__,             "values": ['public', 'private']}),
 ("specs",    {"name": "list_specs",             "desc": "List of specialties recognized in the European Union and European Economic Area according to EU Directive 2005/36/EC",
示例#4
0
     "desc": "Postcode",
     "type": str.__name__,
     "values": None
 }),
 ("city", {
     "name": "city",
     "desc":
     "City name (sometimes refers to a region or a municipality)",
     "type": str.__name__,
     "values": None
 }),
 ("cc", {
     "name": "cc",
     "desc": "Country code (ISO 3166-1 alpha-2 format)",
     "type": str.__name__,
     "values": list(__COUNTRIES.keys())
 }),
 ("country", {
     "name": "country",
     "desc": "Country name",
     "type": str.__name__,
     "values": None
 }),
 ("students", {
     "name": "cap_students",
     "desc": "Measure of capacity by maximum number of students",
     "type": int.__name__,
     "values": None
 }),
 ("enrolled", {
     "name": "cap_students_enrolled",
示例#5
0
            FACACCESS.append(__fac)
            break
    # check countries' metadata
    __path = osp.join(PACKPATH, __fac)
    try:
        assert osp.exists(__path) and osp.isdir(__path)
    except AssertionError:
        continue
    try:
        __finit = osp.join(__path, '__init__.py')
        assert osp.exists(__finit) and osp.isfile(__finit)
    except AssertionError:
        continue
    __all__.append(__cfac)
    # add metadata files to module
    for __cc in COUNTRIES.keys():
        __src = '%s%s' % (__cc, __cfac)
        for __fmt in ['json', 'py']:
            __fsrc = osp.join(__path, '%s.%s' % (__src, __fmt))
            try:
                assert osp.exists(__fsrc) and osp.isfile(__fsrc)
            except AssertionError:
                pass
            else:
                CCACCESS[__fac].append(__cc)
                break

try:
    del (__fac, __cfac, __path)
    del (__cc, __src, __fmt, __fsrc, __finit)
except:
示例#6
0
def harmoniseService(facility, country=None, gc=None, **kwargs):
    """Generic harmonisation function.

        >>> harmonise.harmoniseService(facility, country = None, gc = None, **kwargs)
    """
    #if facility is None:
    #    facility = list(FACILITIES.keys())
    if not isinstance(facility, string_types):
        raise TypeError(
            "Wrong type for input service - must be the facility type")
    elif not facility in FACILITIES.keys():
        raise IOError(
            "Service type not recognised - must be a string in the list '%s'" %
            list(FACILITIES.keys()))
    if country is None:
        country = list(COUNTRIES.keys())
    if not isinstance(country, string_types) and isinstance(country, Sequence):
        for ctry in country:
            try:
                harmoniseService(facility, country=ctry, gc=gc, **kwargs)
            except:
                continue
        return
    elif not isinstance(country, string_types):
        raise TypeError(
            "Wrong type for input country code - must be the ISO 2-letter string"
        )
    elif not country in COUNTRIES.keys():
        raise IOError(
            "Country code not recognised - must be a code of the '%s' area(s)"
            % list(COUNTRIES.keys()))
    if not (gc is None or isinstance(gc, (string_types, Mapping))):
        raise TypeError(
            "Coder type not recognised - must be a dictionary or a single string"
        )
    CC, METADATNAT = None, {}
    metadir = FACILITIES[facility].get('code')
    # generic name
    ccname = "%s%s" % (country, BASENAME.get(facility, ''))
    # load country-dedicated module wmmhen available
    modname = ccname
    fname = '%s.py' % ccname
    try:
        assert osp.exists(osp.join(__THISDIR, metadir, fname))
        # import_module('%s.%s' % (PACKNAME,modname) )
        imp = import_module('.%s' % modname, '%s.%s' % (PACKNAME, metadir))
    except AssertionError:
        logging.warning(
            "\n! No country py-file '%s' found - will proceed without !" %
            fname)
    except ImportError:
        logging.warning(
            "\n! No country py-module '%s' found - will proceed without !" %
            modname)
    except:
        raise ImportError("No country py-module '%s' loaded" % modname)
    else:
        logging.warning("\n! Country py-module '%s' found !" % imp.__name__)
        try:
            assert imp in sysmod.values()
        except:
            raise ImportError("Country py-module '%s' not loaded correctly" %
                              imp.__name__)
    try:
        # assert 'CC' in dir(imp)
        CC = getattr(imp, 'CC', None)
    except:
        logging.warning("\n! Global variable 'CC' not set - use default !")
    # try:
    #     # assert 'META' in dir(imp)
    #     METADATNAT = getattr(imp, 'META', None)
    #     assert METADATNAT is not None
    # except:
    #     logging.warning("\n! No default metadata dictionary 'META' available !")
    # else:
    #     logging.warning("\n! Default hard-coded metadata dictionary 'META' found !")
    try:
        # assert 'harmonise' in dir(imp)
        harmonise = getattr(imp, HARMONISE, None)
        assert harmonise is not None
    except:
        logging.warning('\n! Generic formatting/harmonisation methods used !')
        harmonise = harmoniseFacilityData
    else:
        logging.warning(
            '\n! Country-specific formatting/harmonisation methods used !')
    if 'methods' not in kwargs:
        kwargs.update({'methods': {p: None for p in PROCESSES}})
    for proc in PROCESSES:
        try:
            # assert proc in dir(imp)
            proc_data = getattr(imp, '%s_data' % proc, None)
            assert proc_data is not None
        except:
            # logging.warning("! no data '%s' method used !" % proc)
            pass  # proc_data = None
        else:
            logging.warning("\n! country-specific '%s_data' method loaded !" %
                            proc)
        finally:
            kwargs['methods'].update({proc: proc_data})
    # load country-dedicated metadata when available
    metadata = None
    metafname = '%s.json' % ccname
    try:
        metafname = osp.join(__THISDIR, metadir, metafname)
        assert osp.exists(metafname)
        with open(metafname, 'r') as fp:
            metadata = Json.load(fp)
    except (AssertionError, FileNotFoundError):
        logging.warning(
            "\n! No metadata JSON-file '%s' found - will proceed without !" %
            metafname)
    else:
        logging.warning("! Ad-hoc metadata found - JSON-file '%s' loaded !" %
                        metafname)
    # define the actual metadata: the one loaded, or the default
    # metadata = metadata or METADATNAT
    if metadata in (None, {}):
        raise IOError('No metadata parsed - this cannot end up well')
    try:
        kwargs.update({'country': {'code': CC or country}})
        if 'options' in kwargs.keys():
            if 'locate' in kwargs['options'].keys():
                kwargs['options']['locate'].update({'gc': gc})
            else:
                kwargs['options'].update({'locate': {'gc': gc}})
        else:
            kwargs.update({'options': {'locate': {'gc': gc}}})
        res = harmonise(facility, metadata, **kwargs)
    except:
        raise IOError("Harmonisation process for country '%s' failed..." %
                      country)
    else:
        logging.warning("\n! Harmonised data for country '%s' generated !" %
                        country)
    return res