Skip to content

Commit

Permalink
MAINT: Stop using XTGeoDialog for logging (#138)
Browse files Browse the repository at this point in the history
  • Loading branch information
tnatt authored Sep 18, 2024
1 parent 1e99dd4 commit 0add100
Show file tree
Hide file tree
Showing 16 changed files with 169 additions and 180 deletions.
15 changes: 15 additions & 0 deletions src/grid3d_maps/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,22 @@
"""Top-level package for grid3d_maps"""

import logging
import sys

try:
from .version import __version__

except ImportError:
__version__ = "0.0.0"

logger = logging.getLogger(__name__)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
std_out_handler = logging.StreamHandler(sys.stdout)
std_out_handler.setFormatter(formatter)
std_out_handler.setLevel(logging.INFO)
logger.addHandler(std_out_handler)

std_err_handler = logging.StreamHandler(sys.stderr)
std_err_handler.setFormatter(formatter)
std_err_handler.setLevel(logging.WARNING)
logger.addHandler(std_err_handler)
10 changes: 5 additions & 5 deletions src/grid3d_maps/aggregate/grid3d_aggregate_map.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import logging
import pathlib
import sys
from typing import List

import numpy as np
import xtgeo
from xtgeo.common import XTGeoDialog

from grid3d_maps.aggregate._config import (
AggregationMethod,
Expand All @@ -23,8 +23,8 @@

from . import _config, _grid_aggregation

_XTG = XTGeoDialog()

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

# Module variables for ERT hook implementation:
DESCRIPTION = (
Expand Down Expand Up @@ -89,15 +89,15 @@ def generate_maps(
"""
Calculate and write aggregated property maps to file
"""
_XTG.say("Reading grid, properties and zone(s)")
logger.info("Reading grid, properties and zone(s)")
grid = xtgeo.grid_from_file(input_.grid)
properties = extract_properties(input_.properties, grid, input_.dates)
_filters = []
if computesettings.all:
_filters.append(("all", None))
if computesettings.zone:
_filters += extract_zonations(zonation, grid)
_XTG.say("Generating Property Maps")
logger.info("Generating Property Maps")
xn, yn, p_maps = _grid_aggregation.aggregate_maps(
create_map_template(map_settings),
grid,
Expand Down
26 changes: 13 additions & 13 deletions src/grid3d_maps/avghc/_compute_avg.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
import getpass
import logging
from time import localtime, strftime

import numpy as np
import numpy.ma as ma
import xtgeo
from xtgeo.common import XTGeoDialog, null_logger
from xtgeo.surface import RegularSurface
from xtgeoviz import quickplot

from ._export_via_fmudataio import export_avg_map_dataio

xtg = XTGeoDialog()
logger = null_logger(__name__)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)


def get_avg(config, specd, propd, dates, zonation, zoned, filterarray):
"""Compute a dictionary with average numpy per date
It will return a dictionary per parameter and eventually dates
"""
logger.info("Dates is unused %s", dates)
logger.debug("Dates is unused %s", dates)

avgd = {}

Expand All @@ -43,12 +43,12 @@ def get_avg(config, specd, propd, dates, zonation, zoned, filterarray):
values=np.zeros((ncol, nrow)),
)

xtg.say("Mapping ...")
logger.info("Mapping ...")
if len(propd) == 0 or len(zoned) == 0:
raise RuntimeError("The dictionary <propd> or <zoned> is zero. Stop")

for zname, zrange in zoned.items():
logger.info("ZNAME and ZRANGE are %s: %s", zname, zrange)
logger.debug("ZNAME and ZRANGE are %s: %s", zname, zrange)
usezonation = zonation
usezrange = zrange

Expand All @@ -68,7 +68,7 @@ def get_avg(config, specd, propd, dates, zonation, zoned, filterarray):
usezrange = 999

if config["computesettings"]["all"] is not True:
logger.info("Skip <%s> (cf. computesettings: all)", zname)
logger.debug("Skip <%s> (cf. computesettings: all)", zname)
continue
else:
if config["computesettings"]["zone"] is not True:
Expand Down Expand Up @@ -102,7 +102,7 @@ def get_avg(config, specd, propd, dates, zonation, zoned, filterarray):
if filename is None:
export_avg_map_dataio(avgd[usename], usename, config)
else:
xtg.say("Map file to {}".format(filename))
logger.info("Map file to {}".format(filename))
avgd[usename].to_file(filename)

return avgd
Expand All @@ -111,7 +111,7 @@ def get_avg(config, specd, propd, dates, zonation, zoned, filterarray):
def do_avg_plotting(config, avgd):
"""Do plotting via matplotlib to PNG (etc) (if requested)"""

xtg.say("Plotting ...")
logger.info("Plotting ...")

for names, xmap in avgd.items():
# 'names' is a tuple as (zname, pname)
Expand All @@ -122,7 +122,7 @@ def do_avg_plotting(config, avgd):

pcfg = _avg_plotsettings(config, zname, pname)

xtg.say(f"Plot to {plotfile}")
logger.info("Plot to {}".format(plotfile))

usevrange = pcfg["valuerange"]

Expand All @@ -131,11 +131,11 @@ def do_avg_plotting(config, avgd):
try:
fau = xtgeo.polygons_from_file(pcfg["faultpolygons"], fformat="guess")
faults = {"faults": fau}
xtg.say("Use fault polygons")
logger.info("Use fault polygons")
except OSError as err:
xtg.say(err)
logger.info(str(err))
faults = None
xtg.say("No fault polygons")
logger.info("No fault polygons")

quickplot(
xmap,
Expand Down
11 changes: 5 additions & 6 deletions src/grid3d_maps/avghc/_compute_hcpfz.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import numpy.ma as ma
from xtgeo.common import XTGeoDialog, null_logger
import logging

xtg = XTGeoDialog()
import numpy.ma as ma

logger = null_logger(__name__)
logger = logging.getLogger(__name__)


def get_hcpfz(config, initd, restartd, dates, hcmode, filterarray):
Expand Down Expand Up @@ -49,7 +48,7 @@ def _get_hcpfz_ecl(config, initd, restartd, dates, hcmode, filterarray):
hcmethod = config["computesettings"]["method"]

if not dates:
xtg.error("Dates are missing. Bug?")
logger.error("Dates are missing. Bug?")
raise RuntimeError("Dates er missing. Bug?")

for date in dates:
Expand Down Expand Up @@ -111,7 +110,7 @@ def _get_hcpfz_ecl(config, initd, restartd, dates, hcmode, filterarray):
if dt1 in hcpfzd and dt2 in hcpfzd:
hcpfzd[cdate] = hcpfzd[dt1] - hcpfzd[dt2]
else:
xtg.warn(
logger.warning(
f"Cannot retrieve data for date {dt1} and/or {dt2}. "
"Some TSTEPs failed?"
)
Expand Down
28 changes: 13 additions & 15 deletions src/grid3d_maps/avghc/_configparser.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
import argparse
import copy
import datetime
import logging
import os.path
import sys

import yaml
from xtgeo.common import XTGeoDialog, null_logger

from grid3d_maps.avghc._loader import ConstructorError, FMUYamlSafeLoader

xtg = XTGeoDialog()

logger = null_logger(__name__)
logger = logging.getLogger(__name__)


def parse_args(args, appname, appdescr):
Expand Down Expand Up @@ -96,7 +94,7 @@ def parse_args(args, appname, appdescr):

if len(args) < 2:
parser.print_help()
print("QUIT")
logger.info("QUIT")
raise SystemExit

return parser.parse_args(args)
Expand All @@ -121,10 +119,10 @@ def yconfig(inputfile, tmp=False, standard=False):
try:
config = yaml.load(stream, Loader=FMUYamlSafeLoader)
except ConstructorError as errmsg:
xtg.error(errmsg)
logger.error(errmsg)
raise SystemExit from errmsg

xtg.say(f"Input config YAML file <{inputfile}> is read...")
logger.info(f"Input config YAML file <{inputfile}> is read...")

# if the file is a temporary file, delete:
if tmp:
Expand Down Expand Up @@ -326,39 +324,39 @@ def yconfig_override(config, args, appname):

if args.eclroot:
newconfig["input"]["eclroot"] = args.eclroot
xtg.say(
logger.info(
"YAML config overruled... eclroot is now: <{}>".format(
newconfig["input"]["eclroot"]
)
)

if args.folderroot:
newconfig["input"]["folderroot"] = args.folderroot
xtg.say(
logger.info(
"YAML config overruled... folderroot is now: <{}>".format(
newconfig["input"]["folderroot"]
)
)

if args.zfile:
newconfig["zonation"]["yamlfile"] = args.zfile
xtg.say(
logger.info(
"YAML config overruled... zfile (yaml) is now: <{}>".format(
newconfig["zonation"]["yamlfile"]
)
)

if args.mapfolder:
newconfig["output"]["mapfolder"] = args.mapfolder
xtg.say(
logger.info(
"YAML config overruled... output:mapfolder is now: <{}>".format(
newconfig["output"]["mapfolder"]
)
)

if args.plotfolder:
newconfig["output"]["plotfolder"] = args.plotfolder
xtg.say(
logger.info(
"YAML config overruled... output:plotfolder is now: <{}>".format(
newconfig["output"]["plotfolder"]
)
Expand Down Expand Up @@ -445,9 +443,9 @@ def yconfig_set_defaults(config, appname):
if appname == "grid3d_hc_thickness":
if "dates" not in newconfig["input"]:
if newconfig["computesettings"]["mode"] in "rock":
xtg.say('No date give, probably OK since "rock" mode)')
logger.info('No date give, probably OK since "rock" mode)')
else:
xtg.warn('Warning: No date given, set date to "unknowndate")')
logger.warning('Warning: No date given, set date to "unknowndate")')

newconfig["input"]["dates"] = ["unknowndate"]

Expand Down Expand Up @@ -509,7 +507,7 @@ def yconfig_addons(config, appname):
if "superranges" in zconfig:
newconfig["zonation"]["superranges"] = zconfig["superranges"]

xtg.say(f"Add configuration to {appname}")
logger.info(f"Add configuration to {appname}")

return newconfig

Expand Down
10 changes: 4 additions & 6 deletions src/grid3d_maps/avghc/_export_via_fmudataio.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
"""General functions that exports maps / plots using fmu-dataio."""

import json
import logging
import os
from pathlib import Path

import fmu.dataio as dataio
from fmu.config import utilities as ut
from xtgeo.common import XTGeoDialog, null_logger

xtg = XTGeoDialog()

logger = null_logger(__name__)
logger = logging.getLogger(__name__)


def _get_global_config(thisconfig):
Expand Down Expand Up @@ -117,7 +115,7 @@ def export_avg_map_dataio(surf, nametuple, config):
workflow="grid3d-maps script average maps",
)
fname = edata.export(surf)
xtg.say(f"Output as fmu-dataio: {fname}")
logger.info(f"Output as fmu-dataio: {fname}")
return fname


Expand Down Expand Up @@ -171,5 +169,5 @@ def export_hc_map_dataio(surf, zname, date, hcmode, config):
workflow="grid3d-maps script hc thickness maps",
)
fname = edata.export(surf)
xtg.say(f"Output as fmu-dataio: {fname}")
logger.info(f"Output as fmu-dataio: {fname}")
return fname
Loading

0 comments on commit 0add100

Please sign in to comment.