Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Outputs fix 2.5 #461

Merged
merged 57 commits into from
Jan 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
57 commits
Select commit Hold shift + click to select a range
edc53c8
Changed window title to only show filename (#456)
rhinoella Oct 12, 2023
6c191ba
Changing temp directory control
rhinoella Oct 26, 2023
cc744b5
Debug
rhinoella Oct 26, 2023
b443fb0
Cwd change
rhinoella Oct 26, 2023
737be49
Fix prev commit
rhinoella Oct 26, 2023
f08f6ee
Debugging
rhinoella Oct 26, 2023
a8ebc69
Attempt to fix test
rhinoella Oct 27, 2023
ddc79b3
Upgrade PySide version to 6.6.0 (#463)
rhinoella Nov 16, 2023
4711503
lint
Nov 16, 2023
eb30d07
Fix IDAaaS Setup Script (#471)
trisyoungs Nov 24, 2023
81a8ce8
Fixes November 2023 (#473)
trisyoungs Nov 27, 2023
789894f
Create base class for output handler
Nov 28, 2023
eb084f4
Run purge in temp dir
Nov 28, 2023
18f4721
Output organising fixes- proper gudfile path
Nov 28, 2023
a8c5aad
Iterator fixes
Nov 28, 2023
90bdd0e
Make each iteration run in new temp dir
Nov 28, 2023
734aeb0
Composition iterator
Nov 28, 2023
ecaa9b8
Iterate by composition
rhinoella Nov 29, 2023
0aaac01
Iterate by composition
rhinoella Nov 30, 2023
1a2c090
Formatting
rhinoella Dec 1, 2023
d7d016b
Fix progress bar
rhinoella Dec 1, 2023
57fa0f7
Merge branch 'develop' into outputs-fix-2.5
rhinoella Dec 1, 2023
989cdc5
Fix merge
rhinoella Dec 1, 2023
ced7477
Fixing tests
rhinoella Dec 4, 2023
5b2943a
Display live output from running processes (#474)
rhinoella Dec 6, 2023
357de84
Fix wavelength iterator
rhinoella Dec 8, 2023
798f084
Fix asserion- invalid use of try except
rhinoella Dec 13, 2023
39dc948
Use POpen instead of run
rhinoella Dec 13, 2023
36f8fbd
Remove print
rhinoella Dec 13, 2023
055759d
Refactor purge file
rhinoella Dec 13, 2023
d22e9a3
Fix composition iterator
rhinoella Dec 13, 2023
0ed0096
Fix wavelength iteration process
rhinoella Dec 13, 2023
3819b2c
Create gudrun worker
rhinoella Dec 13, 2023
e82e0eb
Create gudrun worker
rhinoella Dec 13, 2023
561946d
Fix iterator
rhinoella Dec 13, 2023
8891b07
Fix assertions
rhinoella Dec 13, 2023
b87289a
Improve purge running and fix issue
rhinoella Dec 13, 2023
2b25227
Removing unecessary organise output
rhinoella Dec 14, 2023
212cbd4
Used threading instead of qprocess, altered purge dialog, secured tem…
rhinoella Dec 27, 2023
a1cb695
Refactor
rhinoella Dec 27, 2023
d33497f
Refactor
rhinoella Dec 27, 2023
5b4de4d
Fixes for new changes
rhinoella Dec 27, 2023
f039a59
Fixes for new changes
rhinoella Dec 27, 2023
98b49d3
Fixes for new changes
rhinoella Dec 27, 2023
eba3a54
Remove print
rhinoella Dec 27, 2023
4a63809
Merge branch 'develop' into outputs-fix-2.5
rhinoella Jan 11, 2024
1f05fff
Linting
rhinoella Jan 11, 2024
0c87066
Verbose test
rhinoella Jan 11, 2024
64451f4
Verbose test
rhinoella Jan 11, 2024
621f486
Verbose test
rhinoella Jan 11, 2024
3691716
Fix hanging tests by manually error checking gudrun and stop using po…
rhinoella Jan 11, 2024
99a3a22
Fix hanging tests by manually error checking gudrun and stop using po…
rhinoella Jan 11, 2024
ac72fdc
Fix exception for windows
rhinoella Jan 11, 2024
c1aa7e2
Fixing tests
rhinoella Jan 11, 2024
acae80d
Debugging
rhinoella Jan 11, 2024
c74ec04
Fix test error
rhinoella Jan 11, 2024
eb6239a
Fix test error
rhinoella Jan 12, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .github/workflows/test/action.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
name: Test

env:
ACTIONS_STEP_DEBUG: true

runs:
using: "composite"
steps:
Expand Down Expand Up @@ -32,7 +35,7 @@ runs:
shell: bash
run: |
cd gudpy
nose2 --with-coverage --coverage-report xml --plugin nose2.plugins.junitxml --junit-xml test
nose2 --with-coverage --coverage-report xml --plugin nose2.plugins.junitxml --junit-xml --verbose test

mkdir ../results
mv nose2-junit.xml ../results/nose2-junit-${{ runner.os }}.xml
Expand Down
13 changes: 8 additions & 5 deletions gudpy/core/file_library.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,17 @@ def __init__(self, gudrunFile):

# Collect files of static objects
self.files = {
"Groups file": gudrunFile.instrument.groupFileName,
"Deadtime constants file": (
"Detector Calibration File": (
gudrunFile.instrument.detectorCalibrationFileName
),
"Groups File": gudrunFile.instrument.groupFileName,
"Deadtime Constants File": (
gudrunFile.instrument.deadtimeConstantsFileName
),
"Scattering lengths file": (
"Scattering Lengths File": (
gudrunFile.instrument.neutronScatteringParametersFile
),
"Incident beam spectrum parameters": (
"Incident Beam Spectrum Parameters": (
gudrunFile.beam.filenameIncidentBeamSpectrumParams
),
}
Expand All @@ -68,7 +71,7 @@ def __init__(self, gudrunFile):
# then we also need the nexus definition file.
if dataFileType.lower() == "nxs":
self.files[
"NeXus definition file"
"NeXus Definition File"
] = gudrunFile.instrument.nxsDefinitionFile

# If the Total Cross Section Source of any object uses a file,
Expand Down
20 changes: 12 additions & 8 deletions gudpy/core/gud_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,18 @@ def __init__(self, path):
path : str
Path to the file.
"""

# Handle edge cases - invalid extensions and paths.
if not path:
raise ParserException("Please supply a valid path.")

if not path.endswith(".gud"):
raise ParserException(f"Attempted to parse {path}" +
"\nOnly .gud files can be parsed.")

if not os.path.isfile(path):
raise ParserException(f"{path} is not a valid path.")

self.path = path

# Construct the outpath
Expand Down Expand Up @@ -119,14 +131,6 @@ def __init__(self, path):
self.stream = []
self.output = ""

# Handle edge cases - invalid extensions and paths.
if not self.path.endswith(".gud"):
raise ParserException(f"Attempted to parse {self.path}" +
"\nOnly .gud files can be parsed.")

if not os.path.isfile(self.path):
raise ParserException(f"{self.path} is not a valid path.")

# Parse the GudFile
self.parse()

Expand Down
131 changes: 71 additions & 60 deletions gudpy/core/gudrun_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
from core.element import Element
from core.data_files import DataFiles
from core.purge_file import PurgeFile
from core.output_file_handler import OutputFileHandler
from core.output_file_handler import GudrunOutputHandler
from core.enums import (
CrossSectionSource, Format, Instruments, FTModes, UnitsOfDensity,
MergeWeights, Scales, NormalisationType, OutputUnits,
Expand Down Expand Up @@ -147,36 +147,49 @@ def __init__(self, path=None, format=Format.YAML, config_=False):
"""

# Path and filename of initial input file
self.path = path
self.inputFileDir = os.path.dirname(path)
self.filename = os.path.basename(path)

self.yaml = YAML()
self.format = format

# Construct the outpath of generated input file
self.outpath = "gudpy.txt"
self.outputDir = ""

self.components = Components(components=[])
self.gudrunOutput = None

if isinstance(path, type(None)):
self.instrument = Instrument()
self.path = path

if self.path:
self.inputFileDir = os.path.dirname(path)
self.filename = os.path.basename(path)
self.projectDir = os.path.join(
self.inputFileDir, os.path.splitext(self.filename)[0])
self.instrument = None
self.beam = Beam()
self.normalisation = Normalisation()
self.sampleBackgrounds = []
else:
self.instrument = None
self.instrument = Instrument()
self.beam = Beam()
self.normalisation = Normalisation()
self.sampleBackgrounds = []
self.parse(config_=config_)

self.parse(config_=config_)
self.purged = False
# Parse the GudrunFile.
self.stream = None
self.purgeFile = PurgeFile(self)
self.nexus_processing = NexusProcessing(self)

def checkSaveLocation(self):
return self.path is not None

def setSaveLocation(self, projectDir):
self.projectDir = projectDir
self.inputFileDir = projectDir
self.filename = os.path.basename(projectDir)
self.path = os.path.join(self.projectDir, self.filename)

def __deepcopy__(self, memo):
result = self.__class__.__new__(self.__class__)
memo[id(self)] = result
Expand Down Expand Up @@ -1472,7 +1485,8 @@ def save(self, path='', format=None):
if not format:
format = self.format
if format == Format.TXT:
self.write_out(path=path.replace(path.split(".")[-1], "txt"))
self.write_out(path=path.replace(
path.split(".")[-1], "txt"), overwrite=True)
elif format == Format.YAML:
self.write_yaml(path=path.replace(path.split(".")[-1], "yaml"))

Expand All @@ -1496,16 +1510,26 @@ def write_out(self, path='', overwrite=False, writeParameters=True):
None
"""
if path:
if not overwrite:
assert (not os.path.exists(path))
f = open(
path, "w", encoding="utf-8"
)
elif not overwrite:
assert (not os.path.exists(os.path.join(
self.instrument.GudrunInputFileDir,
self.outpath)
))
f = open(
os.path.join(
self.instrument.GudrunInputFileDir,
self.outpath
), "w", encoding="utf-8")
else:
if not self.path:
self.path = os.path.join(
self.instrument.GudrunInputFileDir,
self.outpath)
f = open(self.path, "w", encoding="utf-8")
if os.path.basename(f.name) == self.outpath:
for sampleBackground in self.sampleBackgrounds:
Expand Down Expand Up @@ -1554,30 +1578,44 @@ def dcs(self, path='', headless=True, iterator=None):
The result of calling gudrun_dcs using subprocess.run.
Can access stdout/stderr from this.
"""
assert (self.instrument.GudrunInputFileDir)

if not path:
path = os.path.basename(self.path)
path = f"./{self.outpath}"

if headless:
with tempfile.TemporaryDirectory() as tmp:
try:
self.setGudrunDir(tmp)
gudrun_dcs = resolve("bin", f"gudrun_dcs{SUFFIX}")
cwd = os.getcwd()
os.chdir(self.instrument.GudrunInputFileDir)
result = subprocess.run(
[gudrun_dcs, path], capture_output=True, text=True
)
if iterator is not None:
self.gudrunOutput = iterator.organiseOutput()
else:
self.gudrunOutput = self.organiseOutput()
self.setGudrunDir(self.gudrunOutput.path)
os.chdir(cwd)
except FileNotFoundError:
os.chdir(cwd)
return False
return result
self.setGudrunDir(tmp)
path = os.path.join(
tmp,
path
)
self.write_out(path)
gudrun_dcs = resolve("bin", f"gudrun_dcs{SUFFIX}")
with subprocess.Popen(
[gudrun_dcs, path], cwd=tmp,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
) as gudrun:
result = gudrun

ERROR_KWDS = ["does not exist", "error", "Error"]

for line in gudrun.stdout:
if [KWD for KWD in ERROR_KWDS if KWD
in line.decode("utf8").rstrip("\n")]:
result.error = line
result.returncode = 1
return result

if gudrun.stderr:
result.stderr = gudrun.stderr
return result

if iterator is not None:
self.gudrunOutput = iterator.organiseOutput()
else:
self.gudrunOutput = self.organiseOutput()
self.setGudrunDir(self.gudrunOutput.path)
return result
else:
if hasattr(sys, '_MEIPASS'):
gudrun_dcs = os.path.join(sys._MEIPASS, f"gudrun_dcs{SUFFIX}")
Expand All @@ -1597,38 +1635,11 @@ def dcs(self, path='', headless=True, iterator=None):
proc,
self.write_out,
[
path,
'',
False
]
)

def process(self, headless=True, iterator=None):
"""
Write out the current state of the file,
and then call gudrun_dcs on the file that
was written out.

Parameters
----------
purge : bool, optional
Should detectors be purged?
Returns
-------
subprocess.CompletedProcess
The result of calling gudrun_dcs using subprocess.run.
Can access stdout/stderr from this.
"""
cwd = os.getcwd()
os.chdir(self.instrument.GudrunInputFileDir)
self.write_out()
dcs = self.dcs(
path=self.outpath,
headless=headless,
iterator=iterator
)
os.chdir(cwd)
return dcs

def purge(self, *args, **kwargs):
"""
Call Purge.purge() to purge the detectors.
Expand Down Expand Up @@ -1662,7 +1673,7 @@ def convertToSample(self, container, persist=False):
return sample

def organiseOutput(self, head="", overwrite=True):
outputHandler = OutputFileHandler(
outputHandler = GudrunOutputHandler(
self, head=head, overwrite=overwrite
)
gudrunOutput = outputHandler.organiseOutput()
Expand Down
31 changes: 17 additions & 14 deletions gudpy/core/iterators/composition.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,8 @@ def __init__(self, gudrunFile):
self.ratio = 0
self.nTotal = 0
self.nCurrent = 0
self.iterationType = self.name
self.nWeightedComponents = 0

"""
Sets component and ratio.
Expand Down Expand Up @@ -169,16 +171,14 @@ def processSingleComponent(self, x, sampleBackground):
component.ratio = x

sampleBackground.samples[0].composition.translate()
self.gudrunFile.process()
self.gudrunFile.dcs(iterator=self)

time.sleep(1)
gudPath = sampleBackground.samples[0].dataFiles[0].replace(
self.gudrunFile.instrument.dataFileType,
"gud"
)

gudFile = GudFile(
os.path.join(
self.gudrunFile.instrument.GudrunInputFileDir, gudPath
self.gudrunFile.gudrunOutput.gudFile(
name=sampleBackground.samples[0].name)
)
)

Expand Down Expand Up @@ -219,16 +219,14 @@ def processTwoComponents(self, x, sampleBackground, totalMolecules):
wcB.ratio = abs(totalMolecules - x)

sampleBackground.samples[0].composition.translate()
self.gudrunFile.process()
self.gudrunFile.dcs(iterator=self)

time.sleep(1)
gudPath = sampleBackground.samples[0].dataFiles[0].replace(
self.gudrunFile.instrument.dataFileType,
"gud"
)

gudFile = GudFile(
os.path.join(
self.gudrunFile.instrument.GudrunInputFileDir, gudPath
self.gudrunFile.gudrunOutput.gudFile(
name=sampleBackground.samples[0].name)
)
)

Expand Down Expand Up @@ -285,7 +283,12 @@ def iterate(self, n=10, rtol=10.):
args=(sb, totalMolecules,)
)

self.gudrunFile.organiseOutput()

def gss(self, f, bounds, n, args=()):
return gss(f, bounds, n, self.maxIterations, self.rtol, args=args)

def organiseOutput(self):
"""
This organises the output of the iteration.
"""
gudrunOutput = self.gudrunFile.organiseOutput()
return gudrunOutput
Loading
Loading