本文整理汇总了Python中mantid.kernel.logger.debug函数的典型用法代码示例。如果您正苦于以下问题:Python debug函数的具体用法?Python debug怎么用?Python debug使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了debug函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _pcolor_func
def _pcolor_func(self, name, *args, **kwargs):
"""
Implementation of pcolor-style methods
:param name: The name of the method
:param args: The args passed from the user
:param kwargs: The kwargs passed from the use
:return: The return value of the pcolor* function
"""
plotfunctions_func = getattr(plotfunctions, name)
if helperfunctions.validate_args(*args):
logger.debug('using plotfunctions')
def _update_data(artists, workspace):
return self._redraw_colorplot(plotfunctions_func,
artists, workspace, **kwargs)
workspace = args[0]
# We return the last mesh so the return type is a single artist like the standard Axes
artists = self.track_workspace_artist(workspace,
plotfunctions_func(self, *args, **kwargs),
_update_data)
try:
return artists[-1]
except TypeError:
return artists
else:
return getattr(Axes, name)(self, *args, **kwargs)
示例2: tricontourf
def tricontourf(self, *args, **kwargs):
"""
If the **mantid** projection is chosen, it can be
used the same as :py:meth:`matplotlib.axes.Axes.tricontourf` for arrays,
or it can be used to plot :class:`mantid.api.MatrixWorkspace`
or :class:`mantid.api.IMDHistoWorkspace`. You can have something like::
import matplotlib.pyplot as plt
from mantid import plots
...
fig, ax = plt.subplots(subplot_kw={'projection':'mantid'})
ax.tricontourf(workspace) #for workspaces
ax.tricontourf(x,y,z) #for arrays
fig.show()
For keywords related to workspaces, see :func:`plotfunctions.tricontourf`
"""
if helperfunctions.validate_args(*args):
logger.debug('using plotfunctions')
workspace = args[0]
return self.track_workspace_artist(workspace,
plotfunctions.tricontourf(self, *args, **kwargs))
else:
return Axes.tricontourf(self, *args, **kwargs)
示例3: recover_selected_checkpoint
def recover_selected_checkpoint(self, selected):
"""
Recover the passed checkpoint
:param selected: String; Checkpoint name to be recovered
"""
# If this is a valid file then it should only be the checkpoint here
if os.path.exists(selected):
selected = os.path.basename(selected)
self.is_recovery_running = True
self.presenter.change_start_mantid_to_cancel_label()
ADS.clear()
# Recover given the checkpoint selected
pid_dir = self.project_recovery.get_pid_folder_to_load_a_checkpoint_from()
selected = selected.replace(" ", "T")
checkpoint = os.path.join(pid_dir, selected)
self.selected_checkpoint = selected
try:
self._start_recovery_of_checkpoint(checkpoint)
except Exception as e:
# Fail "Silently" by setting failed run to true, setting checkpoint to tried and closing the view.
logger.debug("Project Recovery: " + str(e))
self.has_failed_run = True
self._update_checkpoint_tried(selected)
self.presenter.close_view()
示例4: _read_atomic_coordinates
def _read_atomic_coordinates(self, file_obj=None):
"""
Reads atomic coordinates from .out CRYSTAL file.
:param file_obj: file object from which we read
:returns: list with atomic coordinates
"""
coord_lines = []
self._parser.find_first(file_obj=file_obj,
msg="ATOM X(ANGSTROM) Y(ANGSTROM) Z(ANGSTROM)")
file_obj.readline() # Line: *******************************************************************************
while not self._parser.file_end(file_obj=file_obj):
line = file_obj.readline().replace(b"T", b"")
# At the end of this section there is always empty line.
if not line.strip():
break
coord_lines += [line.strip(b"\n")]
for line in coord_lines:
# convert from unicode to str in case of Python 2
temp = str(line.strip(b"\n"))
logger.debug(temp)
return coord_lines
示例5: isthere_dsfinterp
def isthere_dsfinterp(self):
try:
import dsfinterp
except:
logger.debug('Python package dsfinterp is missing (https://pypi.python.org/pypi/dsfinterp)')
return False
return True
示例6: _calculate_parameters
def _calculate_parameters(self):
"""
Calculates the TransformToIqt parameters and saves in a table workspace.
"""
CropWorkspace(InputWorkspace=self._sample,
OutputWorkspace='__TransformToIqt_sample_cropped',
Xmin=self._e_min,
Xmax=self._e_max)
x_data = mtd['__TransformToIqt_sample_cropped'].readX(0)
number_input_points = len(x_data) - 1
num_bins = int(number_input_points / self._number_points_per_bin)
self._e_width = (abs(self._e_min) + abs(self._e_max)) / num_bins
try:
instrument = mtd[self._sample].getInstrument()
analyserName = instrument.getStringParameter('analyser')[0]
analyser = instrument.getComponentByName(analyserName)
if analyser is not None:
logger.debug('Found %s component in instrument %s, will look for resolution there'
% (analyserName, instrument))
resolution = analyser.getNumberParameter('resolution')[0]
else:
logger.debug('No %s component found on instrument %s, will look for resolution in top level instrument'
% (analyserName, instrument))
resolution = instrument.getNumberParameter('resolution')[0]
logger.information('Got resolution from IPF: %f' % resolution)
except (AttributeError, IndexError):
resolution = 0.0175
logger.warning('Could not get resolution from IPF, using default value: %f' % (resolution))
resolution_bins = int(round((2 * resolution) / self._e_width))
if resolution_bins < 5:
logger.warning('Resolution curve has <5 points. Results may be unreliable.')
param_table = CreateEmptyTableWorkspace(OutputWorkspace=self._parameter_table)
param_table.addColumn('int', 'SampleInputBins')
param_table.addColumn('float', 'BinReductionFactor')
param_table.addColumn('int', 'SampleOutputBins')
param_table.addColumn('float', 'EnergyMin')
param_table.addColumn('float', 'EnergyMax')
param_table.addColumn('float', 'EnergyWidth')
param_table.addColumn('float', 'Resolution')
param_table.addColumn('int', 'ResolutionBins')
param_table.addRow([number_input_points, self._number_points_per_bin, num_bins,
self._e_min, self._e_max, self._e_width,
resolution, resolution_bins])
DeleteWorkspace('__TransformToIqt_sample_cropped')
self.setProperty('ParameterWorkspace', param_table)
示例7: errorbar
def errorbar(self, *args, **kwargs):
"""
If the **mantid** projection is chosen, it can be
used the same as :py:meth:`matplotlib.axes.Axes.errorbar` for arrays,
or it can be used to plot :class:`mantid.api.MatrixWorkspace`
or :class:`mantid.api.IMDHistoWorkspace`. You can have something like::
import matplotlib.pyplot as plt
from mantid import plots
...
fig, ax = plt.subplots(subplot_kw={'projection':'mantid'})
ax.errorbar(workspace,'rs',specNum=1) #for workspaces
ax.errorbar(x,y,yerr,'bo') #for arrays
fig.show()
For keywords related to workspaces, see :func:`plotfunctions.errorbar`
"""
if helperfunctions.validate_args(*args):
logger.debug('using plotfunctions')
def _data_update(artists, workspace):
# errorbar with workspaces can only return a single container
container_orig = artists[0]
# It is not possible to simply reset the error bars so
# we have to plot new lines but ensure we don't reorder them on the plot!
orig_idx = self.containers.index(container_orig)
container_orig.remove()
# The container does not remove itself from the containers list
# but protect this just in case matplotlib starts doing this
try:
self.containers.remove(container_orig)
except ValueError:
pass
# this gets pushed back onto the containers list
container_new = plotfunctions.errorbar(self, workspace, **kwargs)
self.containers.insert(orig_idx, container_new)
self.containers.pop()
# update line properties to match original
orig_flat, new_flat = cbook.flatten(container_orig), cbook.flatten(container_new)
for artist_orig, artist_new in zip(orig_flat, new_flat):
artist_new.update_from(artist_orig)
# ax.relim does not support collections...
self._update_line_limits(container_new[0])
self.autoscale()
return container_new
workspace = args[0]
spec_num = self._get_spec_number(workspace, kwargs)
return self.track_workspace_artist(workspace,
plotfunctions.errorbar(self, *args, **kwargs),
_data_update, spec_num=spec_num)
else:
return Axes.errorbar(self, *args, **kwargs)
示例8: start_recovery_thread
def start_recovery_thread(self):
"""
Starts the recovery thread if it is not already running
"""
if not self.pr.recovery_enabled:
logger.debug("Project Recovery: Recovery thread not started as recovery is disabled")
return
if not self.pr.thread_on:
self._timer_thread.start()
self.pr.thread_on = True
示例9: _do_slice_viewer
def _do_slice_viewer(self, names):
"""
Show the sliceviewer window for the given workspaces
:param names: A list of workspace names
"""
for ws in self._ads.retrieveWorkspaces(names, unrollGroups=True):
try:
SliceViewer(ws=ws, parent=self)
except Exception as exception:
logger.warning("Could not open slice viewer for workspace '{}'."
"".format(ws.name()))
logger.debug("{}: {}".format(type(exception).__name__,
exception))
示例10: convert
def convert(self, wavelength_min, wavelength_max, detector_workspace_indexes, monitor_workspace_index,
correct_monitor=False, bg_min=None, bg_max=None):
"""
Run the conversion
Arguments:
workspace_ids: Start and end ranges. Ids to be considered as workspaces. Nested list syntax supported
wavelength_min: min wavelength in x for monitor workspace
wavelength_max: max wavelength in x for detector workspace
detector_workspace_indexes: Tuple of workspace indexes (or tuple of tuple min, max ranges to keep)
monitor_workspace_index: The index of the monitor workspace
correct_monitor: Flag indicating that monitors should have a flat background correction applied
bg_min: x min background in wavelength
bg_max: x max background in wavelength
Returns:
_monitor_ws: A workspace of monitors
"""
# Sanity check inputs.
if wavelength_min >= wavelength_max:
raise ValueError("Wavelength_min must be < wavelength_max min: %s, max: %s" % (wavelength_min, wavelength_max))
if correct_monitor and not all((bg_min, bg_max)):
raise ValueError("Either provide ALL, monitors_to_correct, bg_min, bg_max or none of them")
if all((bg_min, bg_max)) and bg_min >= bg_max:
raise ValueError("Background min must be < Background max")
sum = ConvertToWavelength.sum_workspaces(self.__ws_list)
sum_wavelength= msi.ConvertUnits(InputWorkspace=sum, Target="Wavelength", AlignBins='1')
logger.debug("Monitor detector index %s" % str(monitor_workspace_index))
# Crop out the monitor workspace
_monitor_ws = msi.CropWorkspace(InputWorkspace=sum_wavelength,
StartWorkspaceIndex=monitor_workspace_index,EndWorkspaceIndex=monitor_workspace_index)
# Crop out the detector workspace then chop out the x-ranges of interest.
_detector_ws = ConvertToWavelength.crop_range(sum_wavelength, detector_workspace_indexes)
_detector_ws = msi.CropWorkspace(InputWorkspace=_detector_ws, XMin=wavelength_min, XMax=wavelength_max)
# Apply a flat background
if correct_monitor and all((bg_min, bg_max)):
_monitor_ws = msi.CalculateFlatBackground(InputWorkspace=_monitor_ws,WorkspaceIndexList=0,StartX=bg_min, EndX=bg_max)
msi.DeleteWorkspace(Workspace=sum_wavelength.name())
return (_monitor_ws, _detector_ws)
示例11: test_input_exceptions
def test_input_exceptions(self):
# Run the test only if dsfinterp package is present
try:
import dsfinterp
except:
logger.debug('Python package dsfinterp is missing (https://pypi.python.org/pypi/dsfinterp)')
return
nf = 9
fvalues, workspaces = self.generateWorkspaces(nf) # workspaces sim1 to sim9 (nine workpaces)
# Try passing different number of workspaces and parameter values
try:
fvalueswrong = range(nf-1) # eight values
mantid.simpleapi.DSFinterp(Workspaces=workspaces, ParameterValues=fvalueswrong, LocalRegression=False, TargetParameters=5.5, OutputWorkspaces='outws')
except Exception as e:
self.assertTrue('Number of Workspaces and ParameterValues should be the same' in str(e))
else:
assert False, "Didn't raise any exception"
# Try passing an incompatible workspace
try:
mantid.simpleapi.CreateWorkspace(OutputWorkspace='sim10', DataX='1,2,3', DataY='1,1,1', DataE='0,0,0')
fvalues2 = fvalues+[10,]
workspaces2 = workspaces + ['sim10',]
mantid.simpleapi.DSFinterp(Workspaces=workspaces2, ParameterValues=fvalues2, LocalRegression=False, TargetParameters=5.5, OutputWorkspaces='outws')
except Exception as e:
self.assertTrue('Workspace sim10 incompatible with sim1' in str(e))
else:
assert False, "Didn't raise any exception"
mantid.api.AnalysisDataService.remove('sim10')
#Try passing a target parameter outside range
try:
mantid.simpleapi.DSFinterp(Workspaces=workspaces, ParameterValues=fvalues, LocalRegression=False, TargetParameters=nf+1, OutputWorkspaces='outws')
except Exception as e:
self.assertTrue('Target parameters should lie in' in str(e))
else:
assert False, "Didn't raise any exception"
# Try passing a different number of target parameters and output workspaces
try:
mantid.simpleapi.DSFinterp(Workspaces=workspaces, ParameterValues=fvalues, LocalRegression=False, TargetParameters=[1,2], OutputWorkspaces='outws')
except Exception as e:
self.assertTrue('Number of OutputWorkspaces and TargetParameters should be the same' in str(e))
else:
assert False, "Didn't raise any exception"
self.cleanup(nf)
示例12: transCorr
def transCorr(transrun, i_vs_lam, lambda_min, lambda_max, background_min, background_max, int_min, int_max, detector_index_ranges, i0_monitor_index,
stitch_start_overlap, stitch_end_overlap, stitch_params ):
"""
Perform transmission corrections on i_vs_lam.
return the corrected result.
"""
if isinstance(transrun, MatrixWorkspace) and transrun.getAxis(0).getUnit().unitID() == "Wavelength" :
logger.debug("Using existing transmission workspace.")
_transWS = transrun
else:
logger.debug("Creating new transmission correction workspace.")
# Make the transmission correction workspace.
_transWS = make_trans_corr(transrun, stitch_start_overlap, stitch_end_overlap, stitch_params,
lambda_min, lambda_max, background_min, background_max,
int_min, int_max, detector_index_ranges, i0_monitor_index,)
#got sometimes very slight binning diferences, so do this again:
_i_vs_lam_trans = RebinToWorkspace(WorkspaceToRebin=_transWS, WorkspaceToMatch=i_vs_lam, OutputWorkspace=_transWS.name())
# Normalise by transmission run.
_i_vs_lam_corrected = i_vs_lam / _i_vs_lam_trans
return _i_vs_lam_corrected
示例13: recovery_save
def recovery_save(self):
"""
The function to save a recovery checkpoint
"""
# Set that recovery thread is not running anymore
self.pr.thread_on = False
try:
# Get the interfaces_list
interfaces_list = find_all_windows_that_are_savable()
# Check if there is anything to be saved or not
if len(ADS.getObjectNames()) == 0 and len(interfaces_list) == 0:
logger.debug("Project Recovery: Nothing to save")
self._spin_off_another_time_thread()
return
logger.debug("Project Recovery: Saving started")
# Create directory for save location
recovery_dir = os.path.join(self.pr.recovery_directory_pid,
datetime.datetime.now().strftime('%d-%m-%YT%H-%M-%S'))
if not os.path.exists(recovery_dir):
os.makedirs(recovery_dir)
self._add_lock_file(directory=recovery_dir)
# Save workspaces
self._save_workspaces(directory=recovery_dir)
# Save project
self._save_project(directory=recovery_dir, interfaces_list=interfaces_list)
self._remove_lock_file(directory=recovery_dir)
# Clear the oldest checkpoints
self.pr.remove_oldest_checkpoints()
logger.debug("Project Recovery: Saving finished")
except Exception as e:
if isinstance(e, KeyboardInterrupt):
raise
# Fail and print to debugger
logger.debug("Project Recovery: Failed to save error msg: " + str(e))
# Spin off another timer thread
if not self.pr.closing_workbench:
self._spin_off_another_time_thread()
示例14: scatter
def scatter(self, *args, **kwargs):
"""
If the **mantid** projection is chosen, it can be
used the same as :py:meth:`matplotlib.axes.Axes.scatter` for arrays,
or it can be used to plot :class:`mantid.api.MatrixWorkspace`
or :class:`mantid.api.IMDHistoWorkspace`. You can have something like::
import matplotlib.pyplot as plt
from mantid import plots
...
fig, ax = plt.subplots(subplot_kw={'projection':'mantid'})
ax.scatter(workspace,'rs',specNum=1) #for workspaces
ax.scatter(x,y,'bo') #for arrays
fig.show()
For keywords related to workspaces, see :func:`plotfunctions.scatter`
"""
if helperfunctions.validate_args(*args):
logger.debug('using plotfunctions')
else:
return Axes.scatter(self, *args, **kwargs)
示例15: plot
def plot(self, *args, **kwargs):
"""
If the **mantid** projection is chosen, it can be
used the same as :py:meth:`matplotlib.axes.Axes.plot` for arrays,
or it can be used to plot :class:`mantid.api.MatrixWorkspace`
or :class:`mantid.api.IMDHistoWorkspace`. You can have something like::
import matplotlib.pyplot as plt
from mantid import plots
...
fig, ax = plt.subplots(subplot_kw={'projection':'mantid'})
ax.plot(workspace,'rs',specNum=1) #for workspaces
ax.plot(x,y,'bo') #for arrays
fig.show()
For keywords related to workspaces, see :func:`plotfunctions.plot`.
"""
if helperfunctions.validate_args(*args):
logger.debug('using plotfunctions')
def _data_update(artists, workspace):
# It's only possible to plot 1 line at a time from a workspace
x, y, _, __ = plotfunctions._plot_impl(self, workspace, args, kwargs)
artists[0].set_data(x, y)
self.relim()
self.autoscale()
return artists
workspace = args[0]
spec_num = self._get_spec_number(workspace, kwargs)
return self.track_workspace_artist(
workspace, plotfunctions.plot(self, *args, **kwargs),
_data_update, spec_num)
else:
return Axes.plot(self, *args, **kwargs)