Commit a0efd1bf authored by eric pellegrini's avatar eric pellegrini

Merge branch 'hotfix-1.0.3.d'

parents a5878bca 17e180a1
Pipeline #1167 failed with stages
in 2 minutes and 8 seconds
version 1.0.3.c:
----------------
* redirected the sys.stdout and sys.stderr to the LOGGER
* implemented a write method so as ConsoleHandler behaves as a file-like object
* the job short name appears now explicitely in the saved job files
* small refactoring of MDANSE __init__
* small refactoring of ClassRegistry
* removed the explicit imports of the framework classes
* the plotter show the last loaded data now
* bug fix in rmsd job: the PBC were not applied to the calculation
* bug fix in AtomSelectionConfigurator::get_indexes
* bug fix when saving user definitions
* bug fix with the initial size of the user definitions plugins
* updated the job template writing
......
......@@ -106,10 +106,6 @@ class ClassRegistry(object):
moduleName, _ = os.path.splitext(moduleFile)
if moduleDir not in sys.path:
sys.path.insert(0,moduleDir)
# Any error that may occur here has to be caught. In such case the module is skipped.
try:
filehandler,path,description = imp.find_module(moduleName, [moduleDir])
......
......@@ -135,7 +135,7 @@ class AtomSelectionConfigurator(IConfigurator):
if indexesPerElement.has_key(v):
indexesPerElement[v].extend(self['indexes'][i])
else:
indexesPerElement[v] = self['indexes'][i]
indexesPerElement[v] = self['indexes'][i][:]
return indexesPerElement
......
__all__ = ['AtomSelectionConfigurator',
'AtomTransmutationConfigurator',
'AtomsListConfigurator',
'AxisSelectionConfigurator',
'BasisSelectionConfigurator',
'BooleanConfigurator',
'ComplexNumberConfigurator',
'FloatConfigurator',
'FramesConfigurator',
'GroupingLevelConfigurator',
'InputDirectoryConfigurator',
'InputFileConfigurator',
'InstrumentResolutionConfigurator',
'IntegerConfigurator',
'InterpolationOrderConfigurator',
'MMTKTrajectoryConfigurator',
'McStasInstrumentConfigurator',
'McStasOptionsConfigurator',
'McStasParametersConfigurator',
'MultipleChoicesConfigurator',
'NetCDFInputFileConfigurator',
'OutputDirectoryConfigurator',
'OutputFilesConfigurator',
'PartialChargeConfigurator',
'ProjectionConfigurator',
'PythonObjectConfigurator',
'PythonScriptConfigurator',
'QVectorsConfigurator',
'RangeConfigurator',
'RunningModeConfigurator',
'SingleChoiceConfigurator',
'StringConfigurator',
'TrajectoryVariableConfigurator',
'VectorConfigurator',
'WeightsConfigurator']
__all__ = ['ASCIIFormat', 'NetCDFFormat', 'SVGFormat']
\ No newline at end of file
......@@ -35,4 +35,4 @@ class IHandler(object):
Base class for the handlers of MDANSE logger.
'''
_registry = "handler"
\ No newline at end of file
_registry = "handler"
\ No newline at end of file
__all__ = ['ColorizingStreamHandler', 'LogfileHandler']
\ No newline at end of file
__all__ = ['EmptyData', 'InputFileData', 'MMTKTrajectoryInputData', 'MVITraceInputData', 'NetCDFInputData', 'PeriodicTableInputData']
\ No newline at end of file
__all__ = ['GaussianResolution',
'IdealResolution',
'LorentzianResolution',
'PseudoVoigtResolution',
'SquareResolution',
'TriangularResolution']
\ No newline at end of file
......@@ -292,8 +292,8 @@ class IJob(Configurable):
f.write('################################################################\n')
f.write('\n')
f.write('job = REGISTRY[%r][%r]()\n' % ('job',cls._type))
f.write('job.run(parameters,status=True)')
f.write('%s = REGISTRY[%r][%r]()\n' % (cls._type,'job',cls._type))
f.write('%s.run(parameters,status=True)' % (cls._type))
f.close()
......
......@@ -37,7 +37,7 @@ import numpy
from MDANSE import REGISTRY
from MDANSE.Framework.Jobs.IJob import IJob
from MDANSE.Mathematics.Arithmetic import weight
from MDANSE.MolecularDynamics.Analysis import mean_square_deviation
from MDANSE.MolecularDynamics.Trajectory import read_atoms_trajectory
class RootMeanSquareDeviation(IJob):
"""
......@@ -67,16 +67,12 @@ class RootMeanSquareDeviation(IJob):
def initialize(self):
self.numberOfSteps = self.configuration['frames']['number']
self.numberOfSteps = self.configuration['atom_selection']['selection_length']
self.referenceFrame = self.configuration['reference_frame']['value'] % self.configuration['trajectory']['length']
self._referenceIndex = self.configuration['reference_frame']['value']
# Will store the time.
self._outputData.add("time","line", self.configuration['frames']['time'], units='ps')
self._indexes = self.configuration['atom_selection'].get_indexes()
self._masses = numpy.array([m for masses in self._configuration['atom_selection']['masses'] for m in masses],dtype=numpy.float64)
# Will store the mean square deviation
for element in self.configuration['atom_selection']['unique_names']:
......@@ -90,19 +86,20 @@ class RootMeanSquareDeviation(IJob):
@type index: int.
"""
# get the Frame index
frameIndex = self.configuration['frames']['value'][index]
self.configuration['trajectory']['instance'].universe.setFromTrajectory(self.configuration['trajectory']['instance'], frameIndex)
conf1 = self.configuration['trajectory']['instance'].configuration[self.referenceFrame]
conf2 = self.configuration['trajectory']['instance'].universe.configuration()
indexes = self.configuration['atom_selection']["indexes"][index]
masses = self.configuration['atom_selection']["masses"][index]
rmsd = {}
for k,v in self._indexes.items():
rmsd[k] = mean_square_deviation(conf1.array[v,:],conf2.array[v,:],masses=None,root=False)
series = read_atoms_trajectory(self.configuration["trajectory"]["instance"],
indexes,
first=self.configuration['frames']['first'],
last=self.configuration['frames']['last']+1,
step=self.configuration['frames']['step'],
weights=masses)
# Compute the squared sum of the difference between all the coordinate of atoms i and the reference ones
squaredDiff = numpy.sum((series-series[self._referenceIndex,:])**2,axis=1)
return index, rmsd
return index, squaredDiff
def combine(self, index, x):
"""
......@@ -112,22 +109,28 @@ class RootMeanSquareDeviation(IJob):
#. x (any): The returned result(s) of run_step
"""
# The symbol of the atom.
for element in x.keys():
self._outputData["rmsd_%s" % element][index] = x[element]
element = self.configuration['atom_selection']["names"][index]
self._outputData["rmsd_%s" % element] += x
def finalize(self):
"""
Finalize the job.
"""
weights = self.configuration["weights"].get_weights()
nAtomsPerElement = self.configuration['atom_selection'].get_natoms()
# The RMSDs per element are averaged.
nAtomsPerElement = self.configuration['atom_selection'].get_natoms()
for element, number in nAtomsPerElement.items():
self._outputData["rmsd_%s" % element] /= number
weights = self.configuration["weights"].get_weights()
rmsdTotal = weight(weights,self._outputData,nAtomsPerElement,1,"rmsd_%s")
rmsdTotal = numpy.sqrt(rmsdTotal)
self._outputData.add("rmsd_total","line", rmsdTotal, axis="time", units="nm")
for element, number in nAtomsPerElement.items():
self._outputData["rmsd_%s" % element] = numpy.sqrt(self._outputData["rmsd_%s" % element])
# Write the output variables.
self._outputData.write(self.configuration['output_files']['root'], self.configuration['output_files']['formats'], self._info)
......
__all__ = ['CHARMM',
'Castep',
'DFTB',
'DL_POLY',
'DMol',
'Discover',
'Forcite',
'Generic',
'LAMMPS',
'NAMD',
'PDB',
'VASP',
'XPLOR',
'AngularCorrelation',
'AreaPerMolecule',
'BoxTranslatedTrajectory',
'CenterOfMassesTrajectory',
'CoordinationNumber',
'CroppedTrajectory',
'CurrentCorrelationFunction',
'Density',
'DensityOfStates',
'DensityProfile',
'DipoleAutoCorrelationFunction',
'DynamicCoherentStructureFactor',
'DynamicIncoherentStructureFactor',
'Eccentricity',
'ElasticIncoherentStructureFactor',
'GaussianDynamicIncoherentStructureFactor',
'GeneralAutoCorrelationFunction',
'GlobalMotionFilteredTrajectory',
'McStasVirtualInstrument',
'MeanSquareDisplacement',
'MolecularTrace',
'OrderParameter',
'PairDistributionFunction',
'PositionAutoCorrelationFunction',
'RadiusOfGyration',
'RefoldedMembraneTrajectory',
'RigidBodyTrajectory',
'RootMeanSquareDeviation',
'RootMeanSquareFluctuation',
'SolventAccessibleSurface',
'SpatialDensity',
'StaticStructureFactor',
'StructureFactorFromScatteringFunction',
'Temperature',
'UnfoldedTrajectory',
'VelocityAutoCorrelationFunction',
'Voronoi',
'XRayStaticStructureFactor']
\ No newline at end of file
__all__ = ['LineOutputVariable', 'SurfaceOutputVariable', 'VolumeOutputVariable']
\ No newline at end of file
__all__ = ['AxialProjector','NullProjector', 'PlanarProjector']
\ No newline at end of file
__all__ = ['ApproximateDispersionLatticeQVectors',
'CircularLatticeQVectors',
'CircularQVectors',
'DispersionLatticeQVectors',
'GridQVectors',
'LatticeQvectors',
'LinearLatticeQVectors',
'LinearQVectors',
'MillerIndicesQVectors',
'SphericalLatticeQVectors',
'SphericalQVectors']
\ No newline at end of file
__all__ = ['All',
'Amine',
'AtomFullName',
'AtomIndex',
'AtomName',
'AtomPicked',
'AtomSymbol',
'AtomType',
'Backbone',
'CarboHydrogen',
'CarbonAlpha',
'ChainName',
'Expression',
'HeteroHydrogen',
'Hydroxyl',
'Macromolecule',
'Methyl',
'MoleculeIndex',
'MoleculeName',
'NitroHydrogen',
'NucleotideBase',
'NucleotideName',
'NucleotideType',
'OxyHydrogen',
'PDBFile',
'Phosphate',
'PythonScript',
'ResidueClass',
'ResidueName',
'ResidueType',
'SideChain',
'Sulphate',
'SulphurHydrogen',
'Thiol',
'Within']
\ No newline at end of file
from MDANSE.Framework.Configurators import *
from MDANSE.Framework.Formats import *
from MDANSE.Framework.Handlers import *
from MDANSE.Framework.InputData import *
from MDANSE.Framework.InstrumentResolutions import *
from MDANSE.Framework.Jobs import *
from MDANSE.Framework.OutputVariables import *
from MDANSE.Framework.Projectors import *
from MDANSE.Framework.QVectors import *
from MDANSE.Framework.Selectors import *
import os
from MDANSE import PLATFORM, REGISTRY
REGISTRY.update(os.path.join(os.path.dirname(__file__),"*"))
macrosDirectories = sorted([x[0] for x in os.walk(PLATFORM.macros_directory())][0:])
for d in macrosDirectories:
REGISTRY.update(d)
......@@ -82,6 +82,10 @@ class ConsoleHandler(IHandler, logging.Handler):
@type record: logging.LogRecord
"""
record.msg = record.msg.strip()
if not record.msg:
return
self.style.SetTextColour(ConsoleHandler.COLORS.get(record.levelname,wx.BLACK))
# Set the the created text attribute as the default style for the text ctrl.
......@@ -91,5 +95,11 @@ class ConsoleHandler(IHandler, logging.Handler):
self._window.AppendText(self.format(record))
self._window.AppendText("\n")
def write(self,message):
record = logging.LogRecord("console",logging.INFO,None,None,message,None,None,None)
self.emit(record)
REGISTRY["console"] = ConsoleHandler
\ No newline at end of file
__all__ = ['ConsoleHandler', 'DialogHandler']
\ No newline at end of file
......@@ -91,12 +91,17 @@ class MainFrame(wx.Frame):
self.build_dialog()
# Add some handlers to the loggers
LOGGER.add_handler("console", REGISTRY['handler']['console'](self._panels["controller"].pages["logger"]), level="info")
consoleHandler = REGISTRY['handler']['console'](self._panels["controller"].pages["logger"])
LOGGER.add_handler("console", consoleHandler, level="info")
LOGGER.add_handler("dialog", REGISTRY['handler']['dialog'](), level="error")
LOGGER.start()
# Redirect all output to the console logger
sys.stdout = consoleHandler
sys.stderr = consoleHandler
sys.excepthook = excepthook
def build_dialog(self):
self.build_menu()
......@@ -349,7 +354,7 @@ or directly to the MDANSE mailing list:
item = self.GetMenuBar().FindItemById(event.GetId())
converter = item.GetText()
f = JobFrame(self,self._converters[converter],"Trajectory converter")
f = JobFrame(self,self._converters[converter],os.path.join(PLATFORM.home_directory(),"trajectory_conversion.nc"))
f.Show()
def on_open_periodic_table(self, event):
......
......@@ -230,13 +230,13 @@ class DataPanel(wx.Panel):
self.parent._data = self.dataDict[var]['data']
self.show_data()
def show_dataset(self):
def show_dataset(self, index=0):
self.datasetlist.DeleteAllItems()
for i, k in enumerate(self.dataDict.keys()):
self.datasetlist.InsertStringItem(i, k)
self.datasetlist.SetStringItem(i, 1,self.dataDict[k]['basename'])
self.datasetlist.SetStringItem(i, 2,self.dataDict[k]['path'])
self.datasetlist.Select(0, True)
self.datasetlist.Select(index, True)
def show_data(self):
self.datalist.DeleteAllItems()
......@@ -417,6 +417,7 @@ class PlotterFrame(wx.Frame):
self.Destroy()
def on_load_data(self, event=None):
filters = 'NC file (*.nc)|*.nc|All files (*.*)|*.*'
dialog = wx.FileDialog ( self, message = 'Open file...', wildcard=filters, style=wx.MULTIPLE)
if dialog.ShowModal() == wx.ID_CANCEL:
......@@ -447,7 +448,7 @@ class PlotterFrame(wx.Frame):
unique_name = self.unique(basename, self.plugin._dataDict)
self.plugin._dataDict[unique_name]={'data':data,'path':filename,'basename':basename}
self.plugin._dataPanel.show_dataset()
self.plugin._dataPanel.show_dataset(-1)
def unique(self, key, dic):
skey = key
......
......@@ -59,21 +59,18 @@ class UserDefinitionPlugin(ComponentPlugin):
actionsSizer = wx.StaticBoxSizer(sb, wx.HORIZONTAL)
self._udName = wx.TextCtrl(udPanel, wx.ID_ANY, style = wx.TE_PROCESS_ENTER)
applyButton = wx.Button(udPanel, wx.ID_ANY, label="Apply")
saveButton = wx.Button(udPanel, wx.ID_ANY, label="Save")
actionsSizer.Add(self._udName, 1, wx.ALL|wx.EXPAND, 5)
actionsSizer.Add(applyButton, 0, wx.ALL, 5)
actionsSizer.Add(saveButton, 0, wx.ALL, 5)
udPanel.SetSizer(actionsSizer)
self._mainPanel.GetSizer().Add(udPanel,0,wx.EXPAND|wx.ALL,5)
self.Bind(wx.EVT_BUTTON, self.on_apply, applyButton)
self.Bind(wx.EVT_BUTTON, lambda evt : self.on_apply(evt,True), saveButton)
self.Bind(wx.EVT_BUTTON, lambda evt : self.on_save(evt), saveButton)
def on_apply(self, event, save=False):
def on_save(self, event):
name = str(self._udName.GetValue().strip())
......@@ -84,7 +81,7 @@ class UserDefinitionPlugin(ComponentPlugin):
value = self.validate()
if value is None:
return
if UD_STORE.has_definition(self._target,self._type,name):
LOGGER('There is already an user-definition with that name.','error',['dialog'])
return
......@@ -92,10 +89,9 @@ class UserDefinitionPlugin(ComponentPlugin):
UD_STORE.set_definition(self._target,self._type,name,value)
PUBLISHER.sendMessage("msg_set_ud",message=None)
UD_STORE.save()
LOGGER('User definition %r successfully set.' % name,'info',['console'])
if save:
UD_STORE.save()
REGISTRY["user_definition"] = UserDefinitionPlugin
__all__ = ['AnimationPlugin',
'AtomSelectionPlugin',
'AtomsListPlugin',
'DataInfoPlugin',
'DensitySuperpositionPlugin',
'MolecularViewerPlugin',
'MviViewerPlugin',
'PartialChargesPlugin',
'PlotterPlugin',
'QVectorsPlugin',
'UserDefinitionPlugin']
\ No newline at end of file
......@@ -92,6 +92,7 @@ class AtomSelectionWidget(UserDefinitionWidget):
self._sizer.Add(panel,1,wx.ALL|wx.EXPAND,5)
self._widgetPanel.GrandParent.Layout()
self._widgetPanel.GrandParent.Refresh()
self.Bind(wx.EVT_BUTTON, self.on_view_definition, view)
self.Bind(wx.EVT_BUTTON, self.on_remove_definition, remove)
......
......@@ -66,7 +66,8 @@ class AtomTransmutationWidget(AtomSelectionWidget):
self._sizer.Add(panel,1,wx.ALL|wx.EXPAND,5)
self._widgetPanel.GrandParent.Layout()
self._widgetPanel.GrandParent.Refresh()
self.Bind(wx.EVT_BUTTON, self.on_view_definition, view)
self.Bind(wx.EVT_BUTTON, self.on_remove_definition, remove)
......
......@@ -132,5 +132,10 @@ class UserDefinitionWidget(IWidget):
def msg_set_ud(self,message):
uds = UD_STORE.filter(self._basename, self._type)
currentSelection = self._availableUDs.GetStringSelection()
self._availableUDs.SetItems(uds)
if currentSelection:
self._availableUDs.SetStringSelection(currentSelection)
__all__ = ['AtomSelectionWidget',
'AtomTransmutationWidget',
'AtomsListWidget',
'BooleanWidget',
'FloatWidget',
'FramesWidget',
'GroupingLevelWidget',
'InputDirectoryWidget',
'InputFileWidget',
'InstrumentResolutionWidget',
'IntegerWidget',
'InterpolationOrderWidget',
'MMTKTrajectoryWidget',
'McStasInstrumentWidget',
'McStasOptionsWidget',
'McStasParametersWidget',
'MultipleChoicesWidget',
'NetCDFInputFileWidget',
'OutputDirectoryWidget',
'OutputFilesWidget',
'PartialChargesWidget',
'ProjectionWidget',
'PythonObjectWidgets',
'QVectorsWidget',
'RangeWidget',
'RunningModeWidget',
'SingleChoiceWidget',
'StringWidget',
'TrajectoryVariableWidget',
'VectorWidget',
'WeightsWidget']
\ No newline at end of file
......@@ -8,18 +8,13 @@ from MDANSE.Externals.pubsub import pub as PUBLISHER
if platform.dist()[0].lower() == "ubuntu":
os.environ["UBUNTU_MENUPROXY"] = "0"
from MDANSE import PLATFORM, REGISTRY
from MDANSE import REGISTRY
from MDANSE.GUI.Plugins.DataPlugin import DataPlugin
from MDANSE.GUI.Plugins.JobPlugin import JobPlugin
from MDANSE.GUI.Handlers import *
from MDANSE.GUI.Plugins import *
from MDANSE.GUI.Widgets import *
macrosDirectories = sorted([x[0] for x in os.walk(PLATFORM.macros_directory())][0:])
for d in macrosDirectories:
REGISTRY.update(d)
REGISTRY.update(os.path.join(os.path.dirname(__file__),"Handlers"))
REGISTRY.update(os.path.join(os.path.dirname(__file__),"Plugins"))
REGISTRY.update(os.path.join(os.path.dirname(__file__),"Widgets"))
for job in REGISTRY["job"].values():
......@@ -30,7 +25,7 @@ for job in REGISTRY["job"].values():
"ancestor" : getattr(job,'ancestor',job.ancestor),
"category" : getattr(job, "category", ("Miscellaneous",)),
"label" : getattr(job, "label", job.__name__)}
kls = type("%sPlugin" % job.__name__, (JobPlugin,), attrs)
REGISTRY[job._type] = kls
......
......@@ -52,8 +52,3 @@ from MMTK import Database
# The default database is still the MMTK one
Database.path.append(os.path.join(PLATFORM.package_directory(), 'Data'))
macrosDirectories = sorted([x[0] for x in os.walk(PLATFORM.macros_directory())][0:])
for d in macrosDirectories:
REGISTRY.update(d)
__version__ = "1.0.3.c"
__version__ = "1.0.3.d"
__date__ = "08-11-2016"
__date__ = "18-11-2016"
__author__ = "Eric Pellegrini"
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment