Skip to content

Commit

Permalink
Take out instr pars file out of initialization
Browse files Browse the repository at this point in the history
And make classes dataclasses
  • Loading branch information
GuiMacielPereira committed Nov 7, 2024
1 parent f7b610e commit 2c550cc
Show file tree
Hide file tree
Showing 5 changed files with 42 additions and 63 deletions.
5 changes: 4 additions & 1 deletion src/mvesuvio/analysis_fitting.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
import jacobi
import time

from mvesuvio.util import handle_config

repoPath = Path(__file__).absolute().parent # Path to the repository


Expand Down Expand Up @@ -1507,7 +1509,8 @@ def extractData(ws, wsRes, ic):


def loadInstrParsFileIntoArray(ic):
data = np.loadtxt(ic.InstrParsPath, dtype=str)[1:].astype(float)
ipFilesPath = Path(handle_config.read_config_var("caching.ipfolder"))
data = np.loadtxt(str(ipFilesPath / ic.instrParsFile), dtype=str)[1:].astype(float)
spectra = data[:, 0]
select_rows = np.where((spectra >= ic.firstSpec) & (spectra <= ic.lastSpec))
instrPars = data[select_rows]
Expand Down
7 changes: 6 additions & 1 deletion src/mvesuvio/analysis_routines.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@
loadRawAndEmptyWsFromUserPath, cropAndMaskWorkspace, \
NeutronComptonProfile, calculate_h_ratio
from mvesuvio.analysis_reduction import VesuvioAnalysisRoutine
from mvesuvio.util import handle_config

from pathlib import Path

def _create_analysis_object_from_current_interface(IC, running_tests=False):
ws = loadRawAndEmptyWsFromUserPath(
Expand Down Expand Up @@ -40,10 +43,12 @@ def _create_analysis_object_from_current_interface(IC, running_tests=False):

profiles_table = create_profiles_table(cropedWs.name()+"_initial_parameters", profiles)

ipFilesPath = Path(handle_config.read_config_var("caching.ipfolder"))

kwargs = {
"InputWorkspace": cropedWs.name(),
"InputProfiles": profiles_table.name(),
"InstrumentParametersFile": str(IC.InstrParsPath),
"InstrumentParametersFile": str(ipFilesPath / IC.instrParsFile),
"HRatioToLowestMass": IC.HToMassIdxRatio if hasattr(IC, 'HRatioToLowestMass') else 0,
"NumberOfIterations": int(IC.noOfMSIterations),
"InvalidDetectors": IC.maskedSpecAllNo.astype(int).tolist(),
Expand Down
44 changes: 20 additions & 24 deletions src/mvesuvio/config/analysis_inputs.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import numpy as np
from dataclasses import dataclass


@dataclass
class LoadVesuvioBackParameters:
def __init__(self, ipFilesPath):
self.ipfile = ipFilesPath / "ip2019.par"
ipfile = "ip2019.par"

runs = "43066-43076" # 77K # The numbers of the runs to be analysed
empty_runs = (
Expand All @@ -16,9 +17,9 @@ def __init__(self, ipFilesPath):
scaleRaw = 1


@dataclass
class LoadVesuvioFrontParameters:
def __init__(self, ipFilesPath):
self.ipfile = ipFilesPath / "ip2018_3.par"
ipfile = "ip2018_3.par"

runs = "43066-43076" # 100K # The numbers of the runs to be analysed
empty_runs = (
Expand All @@ -31,34 +32,34 @@ def __init__(self, ipFilesPath):
scaleRaw = 1


@dataclass
class GeneralInitialConditions:
"""Used to define initial conditions shared by both Back and Forward scattering"""

# Sample slab parameters
vertical_width, horizontal_width, thickness = 0.1, 0.1, 0.001 # Expressed in meters


@dataclass
class BackwardInitialConditions(GeneralInitialConditions):
def __init__(self, ipFilesPath):
self.InstrParsPath = ipFilesPath / "ip2018_3.par"
instrParsFile = "ip2018_3.par"

HToMassIdxRatio = 19.0620008206 # Set to zero or None when H is not present

# Masses, instrument parameters and initial fitting parameters
masses = np.array([12, 16, 27])
# noOfMasses = len(masses)

# Intensities, NCP widths, NCP centers
initPars = np.array([1, 12, 0.0, 1, 12, 0.0, 1, 12.5, 0.0])
bounds = np.array(
[
[0, np.nan],
[0, None],
[8, 16],
[-3, 1],
[0, np.nan],
[0, None],
[8, 16],
[-3, 1],
[0, np.nan],
[0, None],
[11, 14],
[-3, 1],
]
Expand All @@ -83,31 +84,28 @@ def __init__(self, ipFilesPath):
multiple_scattering_order = 2
number_of_events = 1.0e5

# Original data uses histogram data instead of point data
runHistData = True
normVoigt = False


@dataclass
class ForwardInitialConditions(GeneralInitialConditions):
def __init__(self, ipFilesPath):
self.InstrParsPath = ipFilesPath / "ip2018_3.par"

instrParsFile = "ip2018_3.par"

masses = np.array([1.0079, 12, 16, 27])

# Intensities, NCP widths, NCP centers
initPars = np.array([1, 4.7, 0, 1, 12.71, 0.0, 1, 8.76, 0.0, 1, 13.897, 0.0])
bounds = np.array(
[
[0, np.nan],
[0, None],
[3, 6],
[-3, 1],
[0, np.nan],
[0, None],
[12.71, 12.71],
[-3, 1],
[0, np.nan],
[0, None],
[8.76, 8.76],
[-3, 1],
[0, np.nan],
[0, None],
[13.897, 13.897],
[-3, 1],
]
Expand All @@ -131,11 +129,8 @@ def __init__(self, ipFilesPath):
multiple_scattering_order = 2
number_of_events = 1.0e5

# Original data uses histogram data instead of point data
runHistData = True
normVoigt = False


@dataclass
class YSpaceFitInitialConditions:
showPlots = True
symmetrisationFlag = True
Expand All @@ -147,6 +142,7 @@ class YSpaceFitInitialConditions:
maskTypeProcedure = "NAN" # Options: 'NCP', 'NAN', None


@dataclass
class UserScriptControls:
runRoutine = True

Expand Down
7 changes: 3 additions & 4 deletions src/mvesuvio/main/analysis_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,14 @@

def run(yes_to_all=False):
inputs_path = Path(handle_config.read_config_var("caching.inputs"))
ipFilesPath = Path(handle_config.read_config_var("caching.ipfolder"))

ai = import_from_path(inputs_path, "analysis_inputs")

start_time = time.time()

wsBackIC = ai.LoadVesuvioBackParameters(ipFilesPath)
wsFrontIC = ai.LoadVesuvioFrontParameters(ipFilesPath)
bckwdIC = ai.BackwardInitialConditions(ipFilesPath)
wsBackIC = ai.LoadVesuvioBackParameters
wsFrontIC = ai.LoadVesuvioFrontParameters
bckwdIC = ai.BackwardInitialConditions
fwdIC = ai.ForwardInitialConditions
yFitIC = ai.YSpaceFitInitialConditions
userCtr = ai.UserScriptControls
Expand Down
42 changes: 9 additions & 33 deletions src/mvesuvio/util/process_inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,6 @@ def completeICFromInputs(IC, wsIC):
IC.scaleEmpty = wsIC.scaleEmpty
IC.scaleRaw = wsIC.scaleRaw

# When attribute InstrParsPath is not present, set it equal to path from wsIC
try:
IC.InstrParsPath # If present, leave it unaltered
except AttributeError:
IC.InstrParsPath = wsIC.ipfile

# Sort out input and output paths
rawPath, emptyPath = setInputWSForSample(wsIC)

Expand All @@ -70,26 +64,6 @@ def completeICFromInputs(IC, wsIC):
# Default not running preliminary procedure to estimate HToMass0Ratio
IC.runningPreliminary = False

# Create default of not running original version with histogram data
try:
IC.runHistData
except AttributeError:
IC.runHistData = False

# Norm voigt except when comparing with tests
try:
IC.normVoigt
except AttributeError:
IC.normVoigt = True

#Create default for H ratio
# Only for completeness' sake, will be removed anyway
# when transition to new interface is complete
try:
IC.HToMassIdxRatio
except AttributeError:
IC.HToMassIdxRatio = None

return


Expand All @@ -108,23 +82,25 @@ def setInputWSForSample(wsIC):
rawPath = inputWSPath / rawWSName
emptyPath = inputWSPath / emptyWSName

ipFilesPath = Path(handle_config.read_config_var("caching.ipfolder"))

if not wsHistoryMatchesInputs(wsIC.runs, wsIC.mode, wsIC.ipfile, rawPath):
saveWSFromLoadVesuvio(wsIC.runs, wsIC.mode, wsIC.ipfile, rawPath)
saveWSFromLoadVesuvio(wsIC.runs, wsIC.mode, str(ipFilesPath/wsIC.ipfile), rawPath)

if not wsHistoryMatchesInputs(wsIC.empty_runs, wsIC.mode, wsIC.ipfile, emptyPath):
saveWSFromLoadVesuvio(wsIC.empty_runs, wsIC.mode, wsIC.ipfile, emptyPath)
saveWSFromLoadVesuvio(wsIC.empty_runs, wsIC.mode, str(ipFilesPath/wsIC.ipfile), emptyPath)

return rawPath, emptyPath


def getRunningMode(wsIC):
if wsIC.__class__.__name__ == "LoadVesuvioBackParameters":
if wsIC.__name__ == "LoadVesuvioBackParameters":
runningMode = "backward"
elif wsIC.__class__.__name__ == "LoadVesuvioFrontParameters":
elif wsIC.__name__ == "LoadVesuvioFrontParameters":
runningMode = "forward"
else:
raise ValueError(
f"Input class for loading workspace not valid: {wsIC.__class__.__name__}"
f"Input class for loading workspace not valid: {wsIC.__name__}"
)
return runningMode

Expand Down Expand Up @@ -177,9 +153,9 @@ def wsHistoryMatchesInputs(runs, mode, ipfile, localPath):
return False

saved_ipfile_name = ntpath.basename(metadata.getPropertyValue("InstrumentParFile"))
if saved_ipfile_name != ipfile.name:
if saved_ipfile_name != ipfile:
logger.notice(
f"IP files in saved workspace did not match: {saved_ipfile_name} and {ipfile.name}"
f"IP files in saved workspace did not match: {saved_ipfile_name} and {ipfilename}"
)
return False

Expand Down

0 comments on commit 2c550cc

Please sign in to comment.