Skip to content

Commit

Permalink
More algs. Refs #11824
Browse files Browse the repository at this point in the history
  • Loading branch information
AndreiSavici committed May 26, 2015
1 parent fe8d63a commit b420ad5
Show file tree
Hide file tree
Showing 35 changed files with 329 additions and 286 deletions.
@@ -1,12 +1,13 @@
#pylint: disable=no-init
from mantid.simpleapi import *
from mantid.api import PythonAlgorithm, AlgorithmFactory, PropertyMode, MatrixWorkspaceProperty, \
WorkspaceGroupProperty, InstrumentValidator, WorkspaceUnitValidator
from mantid.kernel import StringListValidator, StringMandatoryValidator, IntBoundedValidator, \
from mantid.kernel import StringListValidator, StringMandatoryValidator, \
FloatBoundedValidator, Direction, logger, CompositeValidator
from mantid import config
import math, os.path, numpy as np

import math, numpy as np

#pylint: disable=too-many-instance-attributes
class CylinderPaalmanPingsCorrection(PythonAlgorithm):

_sample_ws_name = None
Expand All @@ -24,7 +25,13 @@ class CylinderPaalmanPingsCorrection(PythonAlgorithm):
_emode = None
_efixed = 0.0
_output_ws_name = None

_elastic = None
_use_can = None
_angles = None
_beam_width = None
_beam_height = None
_waves = None
_interpolate = None

def category(self):
return "Workflow\\MIDAS;PythonAlgorithms;CorrectionFunctions\\AbsorptionCorrections"
Expand All @@ -37,13 +44,10 @@ def summary(self):
def PyInit(self):
ws_validator = CompositeValidator([WorkspaceUnitValidator('Wavelength'), InstrumentValidator()])

self.declareProperty(MatrixWorkspaceProperty('SampleWorkspace', '',
direction=Direction.Input,
validator=ws_validator),
self.declareProperty(MatrixWorkspaceProperty('SampleWorkspace', '', direction=Direction.Input, validator=ws_validator),
doc='Name for the input sample workspace')

self.declareProperty(name='SampleChemicalFormula', defaultValue='',
validator=StringMandatoryValidator(),
self.declareProperty(name='SampleChemicalFormula', defaultValue='',validator=StringMandatoryValidator(),
doc='Sample chemical formula')
self.declareProperty(name='SampleNumberDensity', defaultValue=0.1,
validator=FloatBoundedValidator(0.0),
Expand All @@ -54,9 +58,9 @@ def PyInit(self):
doc='Sample outer radius')

self.declareProperty(MatrixWorkspaceProperty('CanWorkspace', '',
direction=Direction.Input,
optional=PropertyMode.Optional,
validator=ws_validator),
direction=Direction.Input,
optional=PropertyMode.Optional,
validator=ws_validator),
doc="Name for the input container workspace")

self.declareProperty(name='CanChemicalFormula', defaultValue='',
Expand Down Expand Up @@ -84,11 +88,10 @@ def PyInit(self):
self.declareProperty(name='Efixed', defaultValue=1.0,
doc='Analyser energy')

self.declareProperty(WorkspaceGroupProperty('OutputWorkspace', '',
direction=Direction.Output),
self.declareProperty(WorkspaceGroupProperty('OutputWorkspace', '',direction=Direction.Output),
doc='The output corrections workspace group')


#pylint: disable=too-many-locals
def PyExec(self):

from IndirectImport import is_supported_f2py_platform, import_f2py
Expand Down Expand Up @@ -153,11 +156,11 @@ def PyExec(self):

for angle_idx in range(number_angles):
kill, ass, assc, acsc, acc = cylabs.cylabs(self._step_size, beam, ncan, radii,
density, sigs, siga, self._angles[angle_idx], self._elastic, self._waves, angle_idx, wrk, 0)
density, sigs, siga, self._angles[angle_idx],
self._elastic, self._waves, angle_idx, wrk, 0)

if kill == 0:
logger.information('Angle %d: %f successful' % (angle_idx+1, self._angles[angle_idx]))

data_ass = np.append(data_ass, ass)
data_assc = np.append(data_assc, assc)
data_acsc = np.append(data_acsc, acsc)
Expand All @@ -167,7 +170,7 @@ def PyExec(self):
raise ValueError('Angle ' + str(angle_idx) + ' : ' + str(self._angles[angle_idx]) + ' *** failed : Error code ' + str(kill))

sample_logs = {'sample_shape': 'cylinder', 'sample_filename': self._sample_ws_name,
'sample_inner_radius': self._sample_inner_radius, 'sample_outer_radius': self._sample_outer_radius}
'sample_inner_radius': self._sample_inner_radius, 'sample_outer_radius': self._sample_outer_radius}
dataX = self._waves * number_angles

# Create the output workspaces
Expand Down Expand Up @@ -311,10 +314,10 @@ def _interpolate_corrections(self, workspaces):
@param workspaces List of correction workspaces to interpolate
"""

for ws in workspaces:
for wks in workspaces:
SplineInterpolation(WorkspaceToMatch=self._sample_ws_name,
WorkspaceToInterpolate=ws,
OutputWorkspace=ws,
WorkspaceToInterpolate=wks,
OutputWorkspace=wks,
OutputWorkspaceDeriv='')


Expand All @@ -327,22 +330,22 @@ def _copy_detector_table(self, workspaces):

instrument = mtd[self._sample_ws_name].getInstrument().getName()

for ws in workspaces:
LoadInstrument(Workspace=ws,
for wks in workspaces:
LoadInstrument(Workspace=wks,
InstrumentName=instrument)

CopyDetectorMapping(WorkspaceToMatch=self._sample_ws_name,
WorkspaceToRemap=ws,
WorkspaceToRemap=wks,
IndexBySpectrumNumber=True)


def _add_sample_logs(self, ws, sample_logs):
def _add_sample_logs(self, wks, sample_logs):
"""
Add a dictionary of logs to a workspace.
The type of the log is inferred by the type of the value passed to the log.
@param ws - workspace to add logs too.
@param wks - workspace to add logs too.
@param sample_logs - dictionary of logs to append to the workspace.
"""

Expand All @@ -354,7 +357,7 @@ def _add_sample_logs(self, ws, sample_logs):
else:
log_type = 'String'

AddSampleLog(Workspace=ws, LogName=key, LogType=log_type, LogText=str(value))
AddSampleLog(Workspace=wks, LogName=key, LogType=log_type, LogText=str(value))


# Register algorithm with Mantid
Expand Down
Expand Up @@ -6,6 +6,7 @@
import time
import os

#pylint: disable=too-many-instance-attributes
class ExportExperimentLog(PythonAlgorithm):

""" Algorithm to export experiment log
Expand Down Expand Up @@ -109,6 +110,7 @@ def PyExec(self):

return

#pylint: disable=too-many-branches
def _processInputs(self):
""" Process input properties
"""
Expand All @@ -123,15 +125,15 @@ def _processInputs(self):
ops = self.getProperty("SampleLogOperation").value

if len(self._sampleLogNames) != len(ops):
raise NotImplementedError("Size of sample log names and sample operations are unequal!")
raise RuntimeError("Size of sample log names and sample operations are unequal!")
self._sampleLogOperations = []
for i in xrange(len(self._sampleLogNames)):
value = ops[i]
self._sampleLogOperations.append(value)
# ENDFOR

if len(self._headerTitles) > 0 and len(self._headerTitles) != len(self._sampleLogNames):
raise NotImplementedError("Input header titles have a different length to sample log names")
raise RuntimeError("Input header titles have a different length to sample log names")

# Output file format
self._fileformat = self.getProperty("FileFormat").value
Expand All @@ -151,7 +153,7 @@ def _processInputs(self):
if os.path.exists(self._logfilename) is False:
self._filemode = "new"
if len(self._headerTitles) == 0:
raise NotImplementedError("Without specifying header title, unable to new a file.")
raise RuntimeError("Without specifying header title, unable to new a file.")
self.log().debug("Log file %s does not exist. So file mode is NEW." % (self._logfilename))
else:
self._filemode = self.getProperty("FileMode").value
Expand All @@ -160,7 +162,7 @@ def _processInputs(self):
# Examine the file mode
if self._filemode == "new" or self._filemode == "append":
if len(self._headerTitles) != len(self._sampleLogNames):
raise NotImplementedError("In mode new or append, there must be same number of sample titles and names")
raise RuntimeError("In mode new or append, there must be same number of sample titles and names")

self.log().information("File mode is %s. " % (self._filemode))

Expand Down Expand Up @@ -188,7 +190,7 @@ def _processInputs(self):
overridelist = self.getProperty("OverrideLogValue").value
if len(self._headerTitles) > 0:
if len(overridelist) % 2 != 0:
raise NotImplementedError("Number of items in OverrideLogValue must be even.")
raise RuntimeError("Number of items in OverrideLogValue must be even.")
self._ovrdTitleValueDict = {}
for i in xrange(len(overridelist)/2):
title = overridelist[2*i]
Expand All @@ -203,7 +205,7 @@ def _createLogFile(self):
""" Create a log file
"""
if len(self._headerTitles) == 0:
raise NotImplementedError("No header title specified. Unable to write a new file.")
raise RuntimeError("No header title specified. Unable to write a new file.")

wbuf = ""
for ititle in xrange(len(self._headerTitles)):
Expand All @@ -217,7 +219,7 @@ def _createLogFile(self):
ofile.write(wbuf)
ofile.close()
except OSError as err:
raise NotImplementedError("Unable to write file %s. Check permission. Error message %s." % (
raise RuntimeError("Unable to write file %s. Check permission. Error message %s." % (
self._logfilename, str(err)))

return
Expand All @@ -233,7 +235,7 @@ def _examineLogFile(self):
lines = logfile.readlines()
logfile.close()
except OSError as err:
raise NotImplementedError("Unable to read existing log file %s. Error: %s." % (
raise RuntimeError("Unable to read existing log file %s. Error: %s." % (
self._logfilename, str(err)))

# Find the title line: first none-empty line
Expand Down Expand Up @@ -273,7 +275,7 @@ def _startNewFile(self):
# Rename the old one: split path from file, new name, and rename
fileName, fileExtension = os.path.splitext(self._logfilename)

now = datetime.datetime.now()
#now = datetime.datetime.now()
nowstr = time.strftime("%Y_%B_%d_%H_%M")

newfilename = fileName + "_" + nowstr + fileExtension
Expand Down Expand Up @@ -330,6 +332,7 @@ def _appendExpLog(self, logvaluedict):

return

#pylint: disable=too-many-branches
def _orderRecordFile(self):
""" Check and order (if necessary) record file
by value of specified log by title
Expand Down Expand Up @@ -426,11 +429,10 @@ def _orderRecordFile(self):
def _reorderExistingFile(self):
""" Re-order the columns of the existing experimental log file
"""
raise NotImplementedError("Too complicated")

return
raise RuntimeError("Too complicated")


#pylint: disable=too-many-branches
def _getSampleLogsValue(self):
""" From the workspace to get the value
"""
Expand Down Expand Up @@ -480,9 +482,9 @@ def _getSampleLogsValue(self):
elif operationtype.lower() == "0":
propertyvalue = logproperty.value[0]
else:
raise NotImplementedError("Operation %s for FloatTimeSeriesProperty %s is not supported." % (operationtype, logname))
raise RuntimeError("Operation %s for FloatTimeSeriesProperty %s is not supported." % (operationtype, logname))
else:
raise NotImplementedError("Class type %d is not supported." % (logclass))
raise RuntimeError("Class type %d is not supported." % (logclass))

key = logname + "-" + operationtype
valuedict[key] = propertyvalue
Expand All @@ -495,7 +497,6 @@ def _convertLocalTimeString(self, utctimestr, addtimezone=True):
""" Convert a UTC time in string to the local time in string
and add
"""
from datetime import datetime
from dateutil import tz

# Make certain that the input is utc time string
Expand Down Expand Up @@ -533,8 +534,8 @@ def _convertLocalTimeString(self, utctimestr, addtimezone=True):
srctimeformat = srctimeformat.split(".")[0]
else:
# Un perceived situation
raise NotImplementedError("Is it possible to have time as %s?" % (utctimestr))
utctime = datetime.strptime(utctimestr, srctimeformat)
raise RuntimeError("Is it possible to have time as %s?" % (utctimestr))
utctime = datetime.datetime.strptime(utctimestr, srctimeformat)
except ValueError as err:
self.log().error("Unable to convert time string %s. Error message: %s" % (utctimestr, str(err)))
raise err
Expand Down
Expand Up @@ -445,15 +445,15 @@ def _writeHeaderFile(self, testdatetime, description):

return

def getLocalTimeShiftInSecond(utctime, localtimezone, logger = None):
def getLocalTimeShiftInSecond(utctime, localtimezone, currentlogger = None):
""" Calculate the difference between UTC time and local time of given
DataAndTime
"""
from datetime import datetime
from dateutil import tz

if logger:
logger.information("Input UTC time = %s" % (str(utctime)))
if currentlogger:
currentlogger.information("Input UTC time = %s" % (str(utctime)))

# Return early if local time zone is UTC
if localtimezone == "UTC":
Expand All @@ -464,8 +464,8 @@ def getLocalTimeShiftInSecond(utctime, localtimezone, logger = None):
to_zone = tz.gettz(localtimezone)

t1str = (str(utctime)).split('.')[0].strip()
if logger:
logger.information("About to convert time string: %s" % t1str)
if currentlogger:
currentlogger.information("About to convert time string: %s" % t1str)
try:
if t1str.count("T") == 1:
utc = datetime.strptime(t1str, '%Y-%m-%dT%H:%M:%S')
Expand Down
Expand Up @@ -59,7 +59,7 @@ def PyInit(self):
self.declareProperty(WorkspaceProperty('OutputWorkspace', "", Direction.Output),
doc="The name of the output workspace.")


#pylint: disable=too-many-locals
def PyExec(self):
instrument_name = self.getPropertyValue('Instrument')
analyser = self.getPropertyValue('Analyser')
Expand Down Expand Up @@ -142,7 +142,7 @@ def PyExec(self):
# Build table of values
for data in zip(output_names, output_values):
table_ws.addRow(list(data))
logger.information(': '.join(map(str, list(data))))
logger.information(': '.join([str(d) for d in data]))

# Remove idf/ipf workspace
DeleteWorkspace(workspace)
Expand All @@ -165,14 +165,14 @@ def _get_efixed(self, workspace):

except ValueError:
# If that fails then get it by taking from group of all detectors
ws = mtd[workspace]
spectra_list = range(0, ws.getNumberHistograms())
wsHandle = mtd[workspace]
spectra_list = range(0, wsHandle.getNumberHistograms())
GroupDetectors(InputWorkspace=workspace,
OutputWorkspace=workspace,
SpectraList=spectra_list)
ws = mtd[workspace]
det = ws.getDetector(0)
efixed = mtd[workspace].getEFixed(det.getID())
wsHandle = mtd[workspace]
det = wsHandle.getDetector(0)
efixed = wsHandle.getEFixed(det.getID())

return efixed

Expand Down

0 comments on commit b420ad5

Please sign in to comment.