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 Update #1- Gudrun Output File Organising #458

Merged
merged 24 commits into from
Oct 10, 2023
Merged
Show file tree
Hide file tree
Changes from 22 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
7efb585
Docstring update
rhinoella Sep 25, 2023
8bd6737
Does not delete/replce existing outputs
rhinoella Sep 25, 2023
7ce29cc
Organised iterator files, fixed some bugs
rhinoella Oct 6, 2023
763fa98
Modified import statements to align with new directory structure
rhinoella Oct 6, 2023
f6a7aed
Stored strings in variables
rhinoella Oct 6, 2023
7967aa5
Uniquify default parameter names
rhinoella Oct 6, 2023
0892691
Created extra util functions for uniquifying names and filenames
rhinoella Oct 6, 2023
b87f924
Output file handling process change
rhinoella Oct 6, 2023
7c953a7
Output file handling process change in main window
rhinoella Oct 6, 2023
fec2fb9
Modifying dialog functions as needed
rhinoella Oct 6, 2023
b282735
Formatting
rhinoella Oct 6, 2023
d78eb94
Removed debugging print statements
rhinoella Oct 6, 2023
3d2b9d7
Removed debugging print statements
rhinoella Oct 6, 2023
cc8522a
fixed duplication of sample background directory
rhinoella Oct 6, 2023
73db138
Documentation and commenting
rhinoella Oct 6, 2023
dee91b2
Documentation and commenting
rhinoella Oct 6, 2023
10cf48f
Fixed iteration counting
rhinoella Oct 6, 2023
f88cab1
Fixed wavelength subtraction iterator
rhinoella Oct 6, 2023
51db72c
Merge branch 'develop' into outputs-fix
rhinoella Oct 6, 2023
a324512
Applied changes to batch processing
rhinoella Oct 6, 2023
ae2b3b2
Attempting to fix windows build
rhinoella Oct 6, 2023
9a027e1
Attempting to fix windows build
rhinoella Oct 6, 2023
fe8edb5
Fix windows build? Make sure dir exists
rhinoella Oct 9, 2023
3352fc4
Workflow fix (#459)
rhinoella Oct 10, 2023
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
40 changes: 27 additions & 13 deletions gudpy/core/gudrun_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@
firstNInts,
nthfloat,
nthint,
resolve
resolve,
uniquifyName
)
from core.instrument import Instrument
from core.beam import Beam
Expand Down Expand Up @@ -145,6 +146,7 @@ def __init__(self, path=None, format=Format.YAML, config_=False):
"""

self.path = path
self.filename = os.path.basename(path)
self.yaml = YAML()
self.format = format

Expand Down Expand Up @@ -856,8 +858,6 @@ def parseSample(self):
str(self.getNextToken()[:-2]).strip()
.replace("SAMPLE", "").strip()
)
if not sample.name:
sample.name = "SAMPLE"
self.consumeWhitespace()
# The number of files and period number are both stored
# on the same line.
Expand Down Expand Up @@ -1063,8 +1063,6 @@ def parseContainer(self):
str(self.getNextToken()[:-2]).strip()
.replace("CONTAINER", "").strip()
)
if not container.name:
container.name = "CONTAINER"
self.consumeWhitespace()

# The number of files and period number are both stored
Expand Down Expand Up @@ -1275,10 +1273,25 @@ def sampleBackgroundHelper(self):
elif "GO" in line:
self.getNextToken()
elif "SAMPLE" in line and firstword(line) == "SAMPLE":
sampleBackground.samples.append(self.makeParse("SAMPLE"))
sample = self.makeParse("SAMPLE")
if not sample.name:
sample.name = uniquifyName(
"SAMPLE",
[s.name for s in sampleBackground.samples],
sep="",
incFirst=True)
sampleBackground.samples.append(sample)
elif "CONTAINER" in line and firstword(line) == "CONTAINER":
container = self.makeParse("CONTAINER")
if not container.name:
container.name = uniquifyName(
"CONTAINER",
[c.name
for c in sampleBackground.samples[-1].containers],
sep="",
incFirst=True)
sampleBackground.samples[-1].containers.append(
self.makeParse("CONTAINER")
container
)
self.consumeWhitespace()
line = self.peekNextToken()
Expand Down Expand Up @@ -1519,12 +1532,13 @@ def dcs(self, path='', headless=True, iterative=False):

Parameters
----------
overwrite : bool, optional
Overwrite the initial file? (default is False).
path : str, optional
Path to parse from (default is empty, which indicates self.path).
purge : bool, optional
Should detectors be purged?
headless : bool, optional
Is this being run through CL or GUI?
iterative : bool, optional
Is Gudrun being iterated?

Returns
-------
subprocess.CompletedProcess
Expand Down Expand Up @@ -1635,9 +1649,9 @@ def naiveOrganise(self):
outputFileHandler = OutputFileHandler(self)
outputFileHandler.naiveOrganise()

def iterativeOrganise(self, head):
def iterativeOrganise(self, nTotal, nCurrent, head):
outputFileHandler = OutputFileHandler(self)
outputFileHandler.iterativeOrganise(head)
outputFileHandler.iterativeOrganise(nTotal, nCurrent, head)

def determineError(self, sample):
gudPath = sample.dataFiles[0].replace(
Expand Down
Empty file.
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,14 @@ def gss(

if (
(abs(bounds[2] - bounds[0]) / min([abs(bounds[0]), abs(bounds[2])]))
< (rtol/100)**2
< (rtol / 100)**2
):
if endIterFunc:
endIterFunc(n)
return (bounds[2] + bounds[1]) / 2

# Calculate a potential centre = c + 2 - GR * (upper-c)
d = bounds[1] + (2 - (1 + math.sqrt(5))/2)*(bounds[2]-bounds[1])
d = bounds[1] + (2 - (1 + math.sqrt(5)) / 2) * (bounds[2] - bounds[1])

# If the new centre evaluates to less than the current
fd1 = f(d, *args)
Expand All @@ -43,7 +43,7 @@ def gss(
if endIterFunc:
endIterFunc(n)
return gss(
f, bounds, n+1, maxN, rtol,
f, bounds, n + 1, maxN, rtol,
args=args, startIterFunc=startIterFunc, endIterFunc=endIterFunc
)
# Otherwise, swap and reverse.
Expand All @@ -52,7 +52,7 @@ def gss(
if endIterFunc:
endIterFunc()
return gss(
f, bounds, n+1, maxN, rtol,
f, bounds, n + 1, maxN, rtol,
args=args, startIterFunc=startIterFunc, endIterFunc=endIterFunc
)

Expand Down Expand Up @@ -103,6 +103,9 @@ class CompositionIterator():
gss(f, bounds, n, args=())
Performs n iterations using cost function f, args and bounds.
"""

name = "IterateByComposition"

def __init__(self, gudrunFile):
self.gudrunFile = gudrunFile
self.components = []
Expand All @@ -118,6 +121,7 @@ def __init__(self, gudrunFile):
ratio : int, optional
Ratio of component.
"""

def setComponent(self, component, ratio=1):
self.components = [component]
self.ratio = ratio
Expand All @@ -132,6 +136,7 @@ def setComponent(self, component, ratio=1):
ratio : int, optional
Ratio of component.
"""

def setComponents(self, components, ratio=1):
self.components = [c for c in components if c]
self.ratio = ratio
Expand All @@ -146,6 +151,7 @@ def setComponents(self, components, ratio=1):
sampleBackground : SampleBackground
Target Sample Background.
"""

def processSingleComponent(self, x, sampleBackground):
self.gudrunFile.sampleBackgrounds = [sampleBackground]

Expand All @@ -165,9 +171,9 @@ def processSingleComponent(self, x, sampleBackground):

time.sleep(1)
gudPath = sampleBackground.samples[0].dataFiles[0].replace(
self.gudrunFile.instrument.dataFileType,
"gud"
)
self.gudrunFile.instrument.dataFileType,
"gud"
)
gudFile = GudFile(
os.path.join(
self.gudrunFile.instrument.GudrunInputFileDir, gudPath
Expand All @@ -177,7 +183,7 @@ def processSingleComponent(self, x, sampleBackground):
if gudFile.averageLevelMergedDCS == gudFile.expectedDCS:
return 0
else:
return (gudFile.expectedDCS-gudFile.averageLevelMergedDCS)**2
return (gudFile.expectedDCS - gudFile.averageLevelMergedDCS)**2

"""
Cost function for processing two components.
Expand All @@ -191,6 +197,7 @@ def processSingleComponent(self, x, sampleBackground):
totalMolecules : float
Sum of molecules of both components.
"""

def processTwoComponents(self, x, sampleBackground, totalMolecules):
self.gudrunFile.sampleBackgrounds = [sampleBackground]
x = abs(x)
Expand All @@ -212,9 +219,9 @@ def processTwoComponents(self, x, sampleBackground, totalMolecules):

time.sleep(1)
gudPath = sampleBackground.samples[0].dataFiles[0].replace(
self.gudrunFile.instrument.dataFileType,
"gud"
)
self.gudrunFile.instrument.dataFileType,
"gud"
)
gudFile = GudFile(
os.path.join(
self.gudrunFile.instrument.GudrunInputFileDir, gudPath
Expand Down Expand Up @@ -244,6 +251,7 @@ def processTwoComponents(self, x, sampleBackground, totalMolecules):
rtol : float
Relative tolerance
"""

def iterate(self, n=10, rtol=10.):
if not self.components or not self.ratio:
return None
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from core.single_param_iterator import SingleParamIterator
from core.iterators.single_param_iterator import SingleParamIterator


class DensityIterator(SingleParamIterator):
Expand All @@ -18,6 +18,8 @@ class DensityIterator(SingleParamIterator):
organiseOutput
Organises the output of the iteration.
"""
name = "IterateByDensity"

def applyCoefficientToAttribute(self, object, coefficient):
"""
Multiplies a sample's density by a given coefficient.
Expand All @@ -32,6 +34,3 @@ def applyCoefficientToAttribute(self, object, coefficient):
"""
# Apply the coefficient to the density.
object.density *= coefficient

def organiseOutput(self, n):
self.gudrunFile.iterativeOrganise(f"IterateByDensity_{n}")
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from core.single_param_iterator import SingleParamIterator
from core.iterators.single_param_iterator import SingleParamIterator


class RadiusIterator(SingleParamIterator):
Expand All @@ -21,6 +21,8 @@ class RadiusIterator(SingleParamIterator):
organiseOutput
Organises the output of the iteration.
"""
name = "IterateByRadius"

def applyCoefficientToAttribute(self, object, coefficient):
if self.targetRadius == "inner":
object.innerRadius *= coefficient
Expand All @@ -29,6 +31,3 @@ def applyCoefficientToAttribute(self, object, coefficient):

def setTargetRadius(self, targetRadius):
self.targetRadius = targetRadius

def organiseOutput(self, n):
self.gudrunFile.iterativeOrganise(f"IterateByRadius_{n}")
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ class SingleParamIterator():
organiseOutput
To be overriden by sub-classes.
"""

def __init__(self, gudrunFile):
"""
Constructs all the necessary attributes for the
Expand All @@ -55,12 +56,12 @@ def performIteration(self, _n):
for sampleBackground in self.gudrunFile.sampleBackgrounds:
for sample in [
s for s in sampleBackground.samples
if s.runThisSample
if s.runThisSample and len(s.dataFiles)
]:
gudPath = sample.dataFiles[0].replace(
self.gudrunFile.instrument.dataFileType,
"gud"
)
self.gudrunFile.instrument.dataFileType,
"gud"
)
gudFile = GudFile(
os.path.join(
self.gudrunFile.instrument.GudrunInputFileDir,
Expand Down Expand Up @@ -89,17 +90,19 @@ def applyCoefficientToAttribute(self, object, coefficient):
"""
pass

def organiseOutput(self, n):
def organiseOutput(self, nTotal, nCurrent):
"""
Stub method to be overriden by sub-classes.
This method should organise the output of the iteration.
This should organises the output of the iteration.

Parameters
----------
n : int
Iteration no.
nTotal : int
Total number of requested iterations
nCurrent : int
Current iteration
"""
pass
self.gudrunFile.iterativeOrganise(
nTotal, nCurrent, self.name)

def iterate(self, n):
"""
Expand All @@ -118,4 +121,4 @@ def iterate(self, n):
self.gudrunFile.process()
time.sleep(1)
self.performIteration(i)
self.organiseOutput(i)
self.organiseOutput(n, i)
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from core.single_param_iterator import SingleParamIterator
from core.iterators.single_param_iterator import SingleParamIterator


class ThicknessIterator(SingleParamIterator):
Expand All @@ -19,13 +19,13 @@ class ThicknessIterator(SingleParamIterator):
organiseOutput
Organises the output of the iteration.
"""

name = "IterateByThickness"

def applyCoefficientToAttribute(self, object, coefficient):
# Determine a new total thickness.
totalThickness = object.upstreamThickness + object.downstreamThickness
totalThickness *= coefficient
# Assign the new thicknesses.
object.downstreamThickness = totalThickness / 2
object.upstreamThickness = totalThickness / 2

def organiseOutput(self, n):
self.gudrunFile.iterativeOrganise(f"IterateByThickness_{n}")
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
import time

from core.gud_file import GudFile
from core.iterators.single_param_iterator import SingleParamIterator


class TweakFactorIterator():
class TweakFactorIterator(SingleParamIterator):
"""
Class to represent a Tweak Factor Iterator.
This class is used for iteratively tweaking by the tweak factor.
Expand All @@ -26,17 +27,8 @@ class TweakFactorIterator():
iterate(n)
Perform n iterations of iterating by tweak factor.
"""
def __init__(self, gudrunFile):
"""
Constructs all the necessary attributes for the
TweakFactorIterator object.

Parameters
----------
gudrunFile : GudrunFile
Input GudrunFile that we will be using for iterating.
"""
self.gudrunFile = gudrunFile
name = "IterateByTweakFactor"

def performIteration(self, _n):
"""
Expand All @@ -52,12 +44,12 @@ def performIteration(self, _n):
for sampleBackground in self.gudrunFile.sampleBackgrounds:
for sample in [
s for s in sampleBackground.samples
if s.runThisSample
if s.runThisSample and len(s.dataFiles)
]:
gudPath = sample.dataFiles[0].replace(
self.gudrunFile.instrument.dataFileType,
"gud"
)
self.gudrunFile.instrument.dataFileType,
"gud"
)
gudFile = GudFile(
os.path.join(
self.gudrunFile.instrument.GudrunInputFileDir,
Expand Down Expand Up @@ -90,4 +82,4 @@ def iterate(self, n):
self.gudrunFile.process(iterative=True)
time.sleep(1)
self.performIteration(i)
self.gudrunFile.iterativeOrganise(f"IterateByTweakFactor_{i+1}")
self.organiseOutput(n, i)
Loading