Commit 83a72c1e authored by eric pellegrini's avatar eric pellegrini

Bug fix with ud

Modified the Singleton class to get rid of module import path problem
parent ffd0bc20
......@@ -322,7 +322,7 @@ class AtomSelectionPlugin(ComponentPlugin):
self._selectionSummary.AppendText("List of selected atoms:\n")
for idx in self._selection:
self._selectionSummary.AppendText("\t%s (MMTK index: %d)\n" % self._atoms[idx].fullName(),self._atoms[idx].index)
self._selectionSummary.AppendText("\t%s (MMTK index: %d)\n" % (self._atoms[idx].fullName(),self._atoms[idx].index))
def insert_keyword_values(self, keyword, values):
......@@ -414,7 +414,7 @@ class AtomSelectionPlugin(ComponentPlugin):
path = os.path.basename(self.parent.trajectory.filename)
ud = REGISTRY['userdefinable']['atom_selection'](path,expression=self._expression,indexes=self._selection)
ud = REGISTRY['user_definition']['atom_selection'](path,expression=self._expression,indexes=self._selection)
UD_STORE[name] = ud
......
......@@ -82,10 +82,7 @@ class AtomTransmutationPlugin(AtomSelectionPlugin):
element = self._elements.GetStringSelection()
ud = REGISTRY['userdefinable']['atom_transmutation'](path,
expression=self._expression,
indexes=self._selection,
element=element)
ud = REGISTRY['user_definition']['atom_transmutation'](path,expression=self._expression,indexes=self._selection,element=element)
UD_STORE[name] = ud
UD_STORE.save()
......
......@@ -149,10 +149,7 @@ class AxisSelectionPlugin(ComponentPlugin):
atomNames1 = tuple([self._atomNames1.GetString(idx) for idx in atomIndexes1])
atomNames2 = tuple([self._atomNames2.GetString(idx) for idx in atomIndexes2])
ud = REGISTRY['userdefinable']['axis_selection'](path,
molecule=molName,
endpoint1=atomNames1,
endpoint2=atomNames2)
ud = REGISTRY['user_definition']['axis_selection'](path,molecule=molName,endpoint1=atomNames1,endpoint2=atomNames2)
UD_STORE[name] = ud
UD_STORE.save()
......
......@@ -157,11 +157,7 @@ class BasisSelectionPlugin(ComponentPlugin):
xAxis = tuple([self._xAxis.GetString(idx) for idx in xAxis])
yAxis = tuple([self._yAxis.GetString(idx) for idx in yAxis])
ud = REGISTRY['userdefinable']['basis_selection'](path,
molecule=molName,
origin=origin,
x_axis=xAxis,
y_axis=yAxis)
ud = REGISTRY['user_definition']['basis_selection'](path,molecule=molName,origin=origin,x_axis=xAxis,y_axis=yAxis)
UD_STORE[name] = ud
UD_STORE.save()
......
......@@ -171,11 +171,11 @@ class QVectorsPanel(wx.Panel):
target = os.path.basename(plugin._trajectory.filename)
ud = REGISTRY['userdefinable']['q_vectors'](target,
generator=self._generator.type,
parameters=self._parameters,
q_vectors=self._grid.GetTable().data,
is_lattice=self._generator.is_lattice)
ud = REGISTRY['user_definition']['q_vectors'](target,
generator=self._generator.type,
parameters=self._parameters,
q_vectors=self._grid.GetTable().data,
is_lattice=self._generator.is_lattice)
UD_STORE[name] = ud
UD_STORE.save()
......
......@@ -33,16 +33,15 @@ Created on Apr 14, 2015
import wx
import wx.aui as wxaui
from MDANSE import UD_STORE
from MDANSE.Core.Error import Error
from MDANSE.Framework.UserDefinitions.IUserDefinition import IUserDefinition
from MDANSE.Framework.UserDefinitionsStore import UD_STORE
from MDANSE.App.GUI.Framework.Plugins.ComponentPlugin import ComponentPlugin
class UserDefinitionViewerPluginError(Error):
pass
class UserDefinitionViewerPlugin(ComponentPlugin):
type = "user_definition_viewer"
......@@ -60,7 +59,7 @@ class UserDefinitionViewerPlugin(ComponentPlugin):
self.build_plugins_tree()
def build_panel(self):
self._treePanel = wx.Panel(self, wx.ID_ANY, size=self.GetSize())
treeSizer = wx.BoxSizer(wx.VERTICAL)
......@@ -102,22 +101,19 @@ class UserDefinitionViewerPlugin(ComponentPlugin):
def set_plugins_tree(self, node, data):
for k, v in data.items():
dataItem = wx.TreeItemData(v)
subnode = self._tree.AppendItem(node, str(k), data=dataItem)
if isinstance(v, IUserDefinition):
dataItem = wx.TreeItemData(v)
subnode = self._tree.AppendItem(node, str(k), data=dataItem)
self.set_plugins_tree(subnode, v)
self._tree.SetItemTextColour(subnode, 'red')
elif isinstance(v, dict):
dataItem = wx.TreeItemData(v)
subnode = self._tree.AppendItem(node, str(k), data=dataItem)
self.set_plugins_tree(subnode, v)
self._tree.SetItemTextColour(subnode, 'blue')
else:
dataItem = wx.TreeItemData(v)
subnode = self._tree.AppendItem(node, str(k), data=dataItem)
self._tree.SetItemTextColour(subnode, 'green')
def on_show_info(self, event):
......
......@@ -42,7 +42,7 @@ class Singleton(type):
Creates (or returns if it has already been instanciated) an instance of the class.
'''
if self not in self.__instances:
self.__instances[self] = super(Singleton, self).__call__(*args, **kwargs)
if self.__name__ not in self.__instances:
self.__instances[self.__name__] = super(Singleton, self).__call__(*args, **kwargs)
return self.__instances[self]
return self.__instances[self.__name__]
......@@ -223,7 +223,7 @@ class HisFile(dict):
class DiscoverConverter(Converter):
"""
Converts a DL_POLY trajectory to a MMTK trajectory.
Converts a Discover trajectory to a MMTK trajectory.
"""
type = 'discover'
......
......@@ -30,18 +30,15 @@ Created on Mar 27, 2015
@author: pellegrini
'''
import cPickle
import os
import time
from MDANSE import PLATFORM, REGISTRY
from MDANSE import REGISTRY
from MDANSE.Core.Error import Error
from MDANSE.Core.Singleton import Singleton
class UserDefinitionError(Error):
pass
class IUserDefinition(object):
class IUserDefinition(dict):
'''
Base class for user definable objects. User definable objects are objects used in MDANSE for
storing information that can be reused later when setting up jobs (e.g. k-vectors defintion,
......@@ -59,7 +56,7 @@ class IUserDefinition(object):
# The base class has no predefined set keywords
_keywords = []
def __init__(self, target):
def __init__(self, target, **kwargs):
'''
The constructor
'''
......@@ -69,6 +66,12 @@ class IUserDefinition(object):
self._creationTime = time.ctime()
self._definition = {}
for k in self._keywords:
try:
self._definition[k] = kwargs[k]
except KeyError:
raise UserDefinitionError("Incomplete user definable object: missing %r key" % k)
@property
def target(self):
......@@ -98,141 +101,3 @@ class IUserDefinition(object):
info = ["Created on: %s\n" % self.creationTime] + ["%s:\n%s\n" % (k,self._definition[k]) for k in self._keywords]
return "".join(info)
class UnicodeDict(dict):
'''
This class implements a specification of a python dict that converts automatically any string key in unicode.
This kind of object is useful when exposed to package such as wxPython that implements string as unicode.
'''
def __contains__(self, item):
'''
Returns True if a given key is found in the dictionary.
If the key is basestring then it will be searched as a unicode string.
:param item: the key to search in the dictionary
:type item: any valid key
'''
if isinstance(item,basestring):
return super(UnicodeDict,self).__contains__(unicode(item))
else:
return super(UnicodeDict,self).__contains__(item)
def __setitem__(self, item, value):
'''
Sets the value of a given key.
If the key is a basestring, it will be converted internally in a unicode objet.
:param item: the key to set in the dictionary
:type item: any valid key
:param value: the value to associate with the key
:type value: any python object
'''
if isinstance(item,basestring):
dict.__setitem__(self, unicode(item),value)
else:
raise KeyError("Invalid key type")
class UserDefinitionStore(UnicodeDict):
'''
This class is used to register, save and delete MDANSE user definitions (a.k.a. UD).
Basically, user definitions are used to keep track of definitions made on a given target. The target can
be a file or any kind of object that has to be associated with the user definitions.
This definitions can be selections of atoms, Q vectors definitions, axis definitions ... The
user definitions are loaded when MDANSE starts through a cPickle file that will store these definitions.
They are stored internally as MDANSE.Framework.UserDefinition.IUserDefinition derived objects in a nested
dictionary whose primary key is the target name, secondary key is the category of the user definition and
tertiary key is the name of the user definition.
'''
__metaclass__ = Singleton
UD_PATH = os.path.join(PLATFORM.application_directory(),"user_definitions.ud")
def load(self):
'''
Load the user definitions.
'''
if not os.path.exists(UserDefinitionStore.UD_PATH):
return
# Try to open the UD file.
try:
f = open(UserDefinitionStore.UD_PATH, "rb")
UD = cPickle.load(f)
# If for whatever reason the pickle file loading failed do not even try to restore it
except:
return
else:
self.update(UD)
f.close()
def save(self):
'''
Save the user definitions.
:param path: the path of the user definitions file.
:type path: str
'''
try:
f = open(UserDefinitionStore.UD_PATH, "wb")
except IOError:
return
else:
cPickle.dump(self, f, protocol=2)
f.close()
def __getitem__(self, item):
'''
Returns a user definition given its target, category and its name.
:return: the user definition if it found or None otherwise
:rtype: a MDANSE.Framework.UserDefinitions.IUserDefinition.IUserDefinition derived class
'''
try:
target, typ, name = item
except ValueError:
raise UserDefinitionError("Invalid key value: must be a 3-tuple")
try:
ud = UnicodeDict.__getitem__(name)
except (KeyError,TypeError):
raise UserDefinitionError('The item %r could not be found' % str(name))
else:
if ud.target != target:
raise UserDefinitionError('Target mismatch between %r and %r' % (target,ud.target))
if ud.type != typ:
raise UserDefinitionError('Type mismatch between %r and %r' % (typ,ud.type))
return ud
def __setitem__(self, item, value):
if not isinstance(value,IUserDefinition):
raise IUserDefinition("Invalid value for user definition: must be a user definable object")
UnicodeDict.__setitem__(self, item,value)
def filter(self,target,typ):
return [k for k,v in self.iteritems() if (v.target==target and v.type==typ)]
UD_STORE = UserDefinitionStore()
\ No newline at end of file
import cPickle
import os
from MDANSE import PLATFORM
from MDANSE.Core.Error import Error
from MDANSE.Core.Singleton import Singleton
from MDANSE.Framework.UserDefinitions.AtomSelectionDefinition import AtomSelectionDefinition
class UserDefinitionsStoreError(Error):
pass
class UnicodeDict(dict):
'''
This class implements a specification of a python dict that converts automatically any string key in unicode.
This kind of object is useful when exposed to package such as wxPython that implements string as unicode.
'''
def __contains__(self, item):
'''
Returns True if a given key is found in the dictionary.
If the key is basestring then it will be searched as a unicode string.
:param item: the key to search in the dictionary
:type item: any valid key
'''
if isinstance(item,basestring):
return super(UnicodeDict,self).__contains__(unicode(item))
else:
return super(UnicodeDict,self).__contains__(item)
def __setitem__(self, item, value):
'''
Sets the value of a given key.
If the key is a basestring, it will be converted internally in a unicode objet.
:param item: the key to set in the dictionary
:type item: any valid key
:param value: the value to associate with the key
:type value: any python object
'''
if isinstance(item,basestring):
dict.__setitem__(self, unicode(item),value)
else:
raise KeyError("Invalid key type")
class UserDefinitionsStore(UnicodeDict):
'''
This class is used to register, save and delete MDANSE user definitions (a.k.a. UD).
Basically, user definitions are used to keep track of definitions made on a given target. The target can
be a file or any kind of object that has to be associated with the user definitions.
This definitions can be selections of atoms, Q vectors definitions, axis definitions ... The
user definitions are loaded when MDANSE starts through a cPickle file that will store these definitions.
They are stored internally as MDANSE.Framework.UserDefinition.IUserDefinition derived objects in a nested
dictionary whose primary key is the target name, secondary key is the category of the user definition and
tertiary key is the name of the user definition.
'''
__metaclass__ = Singleton
UD_PATH = os.path.join(PLATFORM.application_directory(),"user_definitions.ud")
def __init__(self):
UnicodeDict.__init__(self)
self.load()
def load(self):
'''
Load the user definitions.
'''
if not os.path.exists(UserDefinitionsStore.UD_PATH):
return
# # Try to open the UD file.
# try:
# f = open(UserDefinitionsStore.UD_PATH, "rb")
# UD = cPickle.load(f)
#
# # If for whatever reason the pickle file loading failed do not even try to restore it
# except:
# return
#
# else:
# UnicodeDict.update(self,UD)
# f.close()
f = open(UserDefinitionsStore.UD_PATH, "rb")
UD = cPickle.load(f)
UnicodeDict.update(self,UD)
f.close()
def save(self):
'''
Save the user definitions.
:param path: the path of the user definitions file.
:type path: str
'''
try:
f = open(UserDefinitionsStore.UD_PATH, "wb")
except IOError:
return
else:
cPickle.dump(self, f, protocol=2)
f.close()
def __getitem__(self, item):
'''
Returns a user definition given its target, category and its name.
:return: the user definition if it found or None otherwise
:rtype: a MDANSE.Framework.UserDefinitions.IUserDefinition.IUserDefinition derived class
'''
try:
target, typ, name = item
except ValueError:
raise UserDefinitionsStoreError("Invalid key value: must be a 3-tuple")
try:
ud = UnicodeDict.__getitem__(name)
except (KeyError,TypeError):
raise UserDefinitionsStoreError('The item %r could not be found' % str(name))
else:
if ud.target != target:
raise UserDefinitionsStoreError('Target mismatch between %r and %r' % (target,ud.target))
if ud.type != typ:
raise UserDefinitionsStoreError('Type mismatch between %r and %r' % (typ,ud.type))
return ud
def __setitem__(self, item, value):
UnicodeDict.__setitem__(self, item,value)
def filter(self,target,typ):
return [k for k,v in self.iteritems() if (v.target==target and v.type==typ)]
UD_STORE = UserDefinitionsStore()
......@@ -41,7 +41,7 @@ from MDANSE.Logging.Logger import LOGGER
from MDANSE.Core.Preferences import PREFERENCES
from MDANSE.Framework.UserDefinitions.IUserDefinition import UD_STORE
from MDANSE.Framework.UserDefinitionsStore import UD_STORE
import os
......
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