Skip to content

Commit

Permalink
Verbosity (#305)
Browse files Browse the repository at this point in the history
* Replaced all the calls to print() in the source code by calls to logging with an appropriate level

* Added the function WallGoManager.setVerbosity() to allow the user to change the verbosity level

* Fixed the doc string of the configureManager function of the SM and IDM examples

* Added a doc string to setVerbosity

* Removed the print in __init__

* Fixed the warning
  • Loading branch information
benoitlaurent96 authored Oct 18, 2024
1 parent 06103fc commit ef491dc
Show file tree
Hide file tree
Showing 17 changed files with 96 additions and 69 deletions.
2 changes: 1 addition & 1 deletion Models/InertDoubletModel/inertDoubletModel.py
Original file line number Diff line number Diff line change
Expand Up @@ -738,7 +738,7 @@ def configureCollisionIntegration(
inOutCollisionTensor.setIntegrationVerbosity(verbosity)

def configureManager(self, inOutManager: "WallGo.WallGoManager") -> None:
"""Singlet example uses spatial grid size = 20"""
"""IDM example uses spatial grid size = 20"""
super().configureManager(inOutManager)
inOutManager.config.configGrid.spatialGridSize = 20

Expand Down
2 changes: 0 additions & 2 deletions Models/SingletStandardModel_Z2/singletStandardModelZ2.py
Original file line number Diff line number Diff line change
Expand Up @@ -300,11 +300,9 @@ def _configureBenchmarkIntegrals(self) -> None:
thisFileDirectory = os.path.dirname(os.path.abspath(__file__))
self.integrals.Jb.readInterpolationTable(
os.path.join(thisFileDirectory, "interpolationTable_Jb_testModel.txt"),
bVerbose=False,
)
self.integrals.Jf.readInterpolationTable(
os.path.join(thisFileDirectory, "interpolationTable_Jf_testModel.txt"),
bVerbose=False,
)

self.integrals.Jb.disableAdaptiveInterpolation()
Expand Down
2 changes: 1 addition & 1 deletion Models/StandardModel/standardModel.py
Original file line number Diff line number Diff line change
Expand Up @@ -487,7 +487,7 @@ def configureCollisionIntegration(
inOutCollisionTensor.setIntegrationVerbosity(verbosity)

def configureManager(self, inOutManager: "WallGo.WallGoManager") -> None:
"""Singlet example uses spatial grid size = 20"""
"""SM example uses spatial grid size = 20"""
super().configureManager(inOutManager)
inOutManager.config.configGrid.spatialGridSize = 20

Expand Down
2 changes: 0 additions & 2 deletions Models/Yukawa/yukawa.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,8 +180,6 @@ def __init__(self, owningModel: YukawaModel) -> None:
self.owner = owningModel
self.modelParameters = self.owner.modelParameters

print(self.modelParameters)

def evaluate(
self, fields: Fields, temperature: float
) -> float | np.ndarray:
Expand Down
14 changes: 13 additions & 1 deletion Models/wallGoExampleBase.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import copy
import inspect
import sys
import logging

import WallGo

Expand Down Expand Up @@ -110,6 +111,15 @@ def initCommandLineArgs(self) -> argparse.ArgumentParser:
help="""Basis size N override for momentum grid. Values less than equal
to 0 are ignored and we use whatever default the example has defined.""",
)

argParser.add_argument(
"-v",
"--verbose",
type=int,
default=logging.DEBUG,
help="""Set the verbosity level. Must be an int: DEBUG=10, INFO=20,
WARNING=30, ERROR=40. Default is DEBUG.""",
)

argParser.add_argument(
"--recalculateMatrixElements",
Expand Down Expand Up @@ -211,6 +221,8 @@ def runExample(self) -> None: # pylint: disable = R0914, R0915
# Initialise the manager
manager = WallGo.WallGoManager()

manager.setVerbosity(self.cmdArgs.verbose)

# Update the configs
self.configureManager(manager)

Expand Down Expand Up @@ -274,7 +286,7 @@ def runExample(self) -> None: # pylint: disable = R0914, R0915

wallSolverSettings.bIncludeOffEquilibrium = False
print(
f"\n === Begin EOM with off-eq effects ignored ==="
f"\n=== Begin EOM with off-eq effects ignored ==="
)
results = manager.solveWall(wallSolverSettings)
self.processResultsForBenchmark(benchmark, results)
Expand Down
2 changes: 0 additions & 2 deletions src/WallGo/PotentialTools/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,9 @@ def _initalizeIntegralInterpolations() -> None: # pylint: disable=invalid-name

defaultIntegrals.Jb.readInterpolationTable(
getSafePathToResource(config.get("DataFiles", "InterpolationTable_Jb")),
bVerbose=False,
)
defaultIntegrals.Jf.readInterpolationTable(
getSafePathToResource(config.get("DataFiles", "InterpolationTable_Jf")),
bVerbose=False,
)


Expand Down
11 changes: 4 additions & 7 deletions src/WallGo/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""Initialising WallGo package"""

import warnings

# subpackage
from . import PotentialTools

Expand Down Expand Up @@ -34,14 +36,13 @@
try:
import WallGoCollision

print(f"Loaded WallGoCollision package from location: {WallGoCollision.__path__}")
#print(f"Loaded WallGoCollision package from location: {WallGoCollision.__path__}")
_bCollisionModuleAvailable = True # pylint: disable=invalid-name

from .collisionHelpers import *

except ImportError as e:
print(f"Error loading WallGoCollision module: {e}")
print(
warnings.warn(f"Error loading WallGoCollision module: {e}"
"This could indicate an issue with your installation of WallGo or "
"WallGoCollision, or both. This is non-fatal, but you will not be able to"
" utilize collision integration routines."
Expand Down Expand Up @@ -75,7 +76,3 @@ def _initializeInternal() -> None:
_bInitialized = True
else:
raise RuntimeWarning("Warning: Repeated call to WallGo._initializeInternal()")


"""Initialising WallGo"""
_initializeInternal()
3 changes: 2 additions & 1 deletion src/WallGo/boltzmann.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import sys
import typing
from copy import deepcopy
import logging
import numpy as np
import findiff # finite difference methods
from .containers import BoltzmannBackground, BoltzmannDeltas
Expand Down Expand Up @@ -635,7 +636,7 @@ def loadCollisions(self, directoryPath: "pathlib.Path") -> None:
self.basisN,
self.offEqParticles,
)
print(f"Loaded collision data from directory {directoryPath}")
logging.debug(f"Loaded collision data from directory {directoryPath}")
except CollisionLoadError as e:
raise

Expand Down
4 changes: 3 additions & 1 deletion src/WallGo/collisionHelpers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""Conversion between WallGo and WallGoCollision types"""

import logging

from .particle import Particle
from .genericModel import GenericModel
from .exceptions import WallGoError
Expand Down Expand Up @@ -28,7 +30,7 @@ def convertParticleStatistics(statisticsName: str) -> WallGoCollision.EParticleT
elif statisticsName == "Boson":
return WallGoCollision.EParticleType.eBoson
else:
print(
logging.warning(
f'Invalid particle statistic: {statisticsName}. Must be "Fermion" or "Boson".'
)
return WallGoCollision.EParticleType.eNone
Expand Down
21 changes: 12 additions & 9 deletions src/WallGo/equationOfMotion.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import warnings
from typing import Tuple
import copy # for deepcopy
import logging
import numpy as np
import numpy.typing as npt

Expand Down Expand Up @@ -178,7 +179,7 @@ def findWallVelocityDeflagrationHybrid(
self.hydrodynamics.doesPhaseTraceLimitvmax[0]
or self.hydrodynamics.doesPhaseTraceLimitvmax[1]
):
print(
logging.warning(
"""\n Warning: vmax is limited by the maximum temperature chosen in
the phase tracing. WallGo might be unable to find the wall velocity.
Try increasing the maximum temperature! \n"""
Expand Down Expand Up @@ -456,8 +457,8 @@ def solveWall(
# The pressure peak is not enough to stop the wall: no deflagration or
# hybrid solution
if pressureMax < 0:
print("Maximum pressure on wall is negative!")
print(f"{pressureMax=} {wallParamsMax=}")
logging.info("Maximum pressure on wall is negative!")
logging.info(f"{pressureMax=} {wallParamsMax=}")
results.setWallVelocities(None, None, wallVelocityLTE)
results.setWallParams(wallParamsMax)
results.setHydroResults(hydroResultsMax)
Expand Down Expand Up @@ -494,7 +495,7 @@ def solveWall(
# until it's negative.
wallVelocityMin *= 2
if wallVelocityMin >= wallVelocityMax:
print(
logging.warning(
"""EOM warning: the pressure at vw = 0 is positive which indicates
the phase transition cannot proceed. Something might be wrong with
your potential."""
Expand Down Expand Up @@ -750,7 +751,7 @@ def wallPressure(
if wallVelocity > self.hydrodynamics.vJ:
improveConvergence = True

print(f"------------- Trying {wallVelocity=:g} -------------")
logging.info(f"------------- Trying {wallVelocity=:g} -------------")

# Initialize the different data class objects and arrays
zeroPoly = Polynomial(
Expand Down Expand Up @@ -856,7 +857,7 @@ def wallPressure(
multiplier = 1.0

i = 0
print(
logging.debug(
f"{'pressure':>12s} {'error':>12s} {'errorSolver':>12s} {'errTol':>12s} {'cautious':>12s} {'multiplier':>12s}"
)
while True:
Expand Down Expand Up @@ -909,7 +910,7 @@ def wallPressure(
error = np.abs(pressures[-1] - pressures[-2])
errTol = np.maximum(rtol * np.abs(pressure), atol) * multiplier

print(
logging.debug(
f"{pressure:>12g} {error:>12g} {errorSolver:>12g} {errTol:>12g} {improveConvergence:>12} {multiplier:>12g}"
)
i += 1
Expand All @@ -929,7 +930,7 @@ def wallPressure(
else:
break
elif i >= self.maxIterations - 1:
print(
logging.warning(
"Pressure for a wall velocity has not converged to "
"sufficient accuracy with the given maximum number "
"for iterations."
Expand All @@ -953,7 +954,9 @@ def wallPressure(
# If the error decreases too slowly, use the improved algorithm
improveConvergence = True

print(f"Final {pressure=:g}; Final {wallParams=}")
logging.info(f"Final {pressure=:g}")
logging.debug(f"Final {wallParams=}")

return (
pressure,
wallParams,
Expand Down
7 changes: 4 additions & 3 deletions src/WallGo/freeEnergy.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"""

from dataclasses import dataclass
import logging
import numpy as np
import scipy.integrate as scipyint
import scipy.linalg as scipylinalg
Expand Down Expand Up @@ -336,7 +337,7 @@ def spinodalEvent(temperature: float, field: np.ndarray) -> float:
try:
ode.step()
except RuntimeWarning as error:
print(error.args[0] + f" at T={ode.t}")
logging.error(error.args[0] + f" at T={ode.t}")
break
if paranoid:
phaset, potentialEffT = self.effectivePotential.findLocalMinimum(
Expand Down Expand Up @@ -369,7 +370,7 @@ def spinodalEvent(temperature: float, field: np.ndarray) -> float:
if ode.step_size < 1e-16 * T0 or (
TList.size > 0 and ode.t == TList[-1]
):
print(
logging.warning(
f"Step size {ode.step_size} shrunk too small at T={ode.t}, "
f"vev={ode.y}"
)
Expand Down Expand Up @@ -421,7 +422,7 @@ def spinodalEvent(temperature: float, field: np.ndarray) -> float:
or self.minPossibleTemperature[0]
> self.startingTemperature - ode.step_size * 10
):
print(
logging.warning(
"""Warning: the temperature step size seems too large.
Try decreasing temperatureVariationScale."""
)
Expand Down
5 changes: 3 additions & 2 deletions src/WallGo/hydrodynamics.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"""

from typing import Tuple
import logging
import numpy as np
import numpy.typing as npt
from scipy.optimize import root_scalar, root, minimize_scalar
Expand Down Expand Up @@ -69,7 +70,7 @@ def __init__(
try:
self.vJ = self.findJouguetVelocity()
except WallGoError:
print(
logging.warning(
"Couldn't find Jouguet velocity, we continue "
"with the Jouguet velocity of the template model"
)
Expand Down Expand Up @@ -812,7 +813,7 @@ def findHydroBoundaries(
"""
if vwTry < self.vMin:
print(
logging.warning(
"This wall velocity is too small for the chosen nucleation temperature,"
" findHydroBoundaries will return zero."
)
Expand Down
3 changes: 2 additions & 1 deletion src/WallGo/hydrodynamicsTemplateModel.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"""

import warnings
import logging
import numpy as np
from scipy.integrate import solve_ivp
from scipy.optimize import root_scalar, minimize_scalar, OptimizeResult
Expand Down Expand Up @@ -566,7 +567,7 @@ def findHydroBoundaries(self, vwTry: float) -> tuple[float | None, ...]:
to find a solution, returns a tuple of None.
"""
if vwTry < self.vMin:
print(
logging.warning(
"""This wall velocity is too small for the chosen nucleation
temperature. findHydroBoundaries will return zero."""
)
Expand Down
Loading

0 comments on commit ef491dc

Please sign in to comment.