Commit c117286e authored by eric pellegrini's avatar eric pellegrini
Browse files

Merge branch 'feature-sphinx_doc' into 'develop'

Feature sphinx doc

See merge request !26
parents 017616ad fdb9294c
Pipeline #4229 passed with stages
in 36 minutes and 53 seconds
......@@ -1170,12 +1170,4 @@ def _init_mags():
if not MAGS:
_init_mags()
if __name__ == "__main__":
print mg(1.0,'h THz','meV')
print mg(1.0,'meV/h','THz')
print mg(1.0,'hbar rad/ps','meV')
print mg(1.0,'cyc THz','rad/ps')
print mg(1.0,'rad/ps',' cyc THz')
print mg(1.0,'rad/ps',' cyc meV(freq)')
......@@ -122,36 +122,26 @@ if __name__ == "__main__":
from MDANSE.Externals.pyparsing.pyparsing import *
def parse_keyword(token):
print "parse_keyword"
return '"%s"(universe).select' % token[0]
def parse_arguments(token):
print "parse_arguments"
return "(%s)" % str(token)
def operator_and(token):
print "operator_and"
token[0][1] = "&"
return " ".join(token[0])
def operator_or(token):
print "operator_or"
token[0][1] = "|"
return " ".join(token[0])
def parse_expression(self, token):
print "parse_expression"
return "".join([str(t) for t in token])
......@@ -173,5 +163,4 @@ if __name__ == "__main__":
rpar=")")
parsedExpression = expr.transformString(expression)
print parsedExpression
......@@ -33,7 +33,6 @@ Created on Mar 30, 2015
import collections
import operator
from MDANSE import ELEMENTS, REGISTRY
from MDANSE.Framework.UserDefinitionStore import UD_STORE
from MDANSE.Framework.Configurators.IConfigurator import IConfigurator, ConfiguratorError
......@@ -47,7 +46,7 @@ LEVELS["residue"] = {"atom" : 0, "atomcluster" : 1, "molecule" : 1, "nucleotide
LEVELS["chain"] = {"atom" : 0, "atomcluster" : 1, "molecule" : 1, "nucleotidechain" : 3, "peptidechain" : 3, "protein" : 3}
LEVELS["molecule"] = {"atom" : 0, "atomcluster" : 1, "molecule" : 1, "nucleotidechain" : 3, "peptidechain" : 3, "protein" : 4}
class AtomSelectionConfigurator(IConfigurator):
class AtomSelectionConfigurator(IConfigurator):
'''
This configurator allows the selection of a specific set of atoms on which the analysis will be performed.
......@@ -55,82 +54,77 @@ class AtomSelectionConfigurator(IConfigurator):
After the call to :py:meth:`~MDANSE.Framework.Configurators.AtomSelectionConfigurator.AtomSelectionConfigurator.configure` method
the following keys will be available for this configurator
#. value: the input value used to configure this configurator
#. indexes: the sorted (in increasing order) MMTK indexes of the selected atoms
#. indexes: the sorted (in increasing order) MMTK indexes of the selected atoms
#. n_selected_atoms: the number of selected atoms
#. elements: a nested-list of the chemical symbols of the selected atoms. The size of the nested list depends on the
grouping_level selected via :py:class:`~MDANSE.Framework.Configurators.GroupingLevelConfigurator.GroupingLevelConfigurator`
configurator.
#. elements: a nested-list of the chemical symbols of the selected atoms. The size of the nested list depends on the grouping_level selected via :py:class:`~MDANSE.Framework.Configurators.GroupingLevelConfigurator.GroupingLevelConfigurator` configurator.
:note: this configurator depends on :py:class:`~MDANSE.Framework.Configurators.MMTKTrajectoryConfigurator.MMTKTrajectoryConfigurator`
and :py:class:`~MDANSE.Framework.Configurators.GroupingLevelConfigurator.GroupingLevelConfigurator` configurators to be configured
:note: this configurator depends on :py:class:`~MDANSE.Framework.Configurators.MMTKTrajectoryConfigurator.MMTKTrajectoryConfigurator` and :py:class:`~MDANSE.Framework.Configurators.GroupingLevelConfigurator.GroupingLevelConfigurator` configurators to be configured
'''
_default = "all"
def configure(self, value):
'''
Configure an input value.
The value must be a string that can be either an atom selection string or a valid user
definition.
The value must be a string that can be either an atom selection string or a valid user definition.
:param value: the input value
:type value: str
'''
trajConfig = self._configurable[self._dependencies['trajectory']]
if value is None:
value = ['all']
if isinstance(value,basestring):
value = [value]
if not isinstance(value,(list,tuple)):
raise ConfiguratorError("Invalid input value.")
self["value"] = value
indexes = set()
for v in value:
if UD_STORE.has_definition(trajConfig["basename"],"atom_selection",v):
ud = UD_STORE.get_definition(trajConfig["basename"],"atom_selection",v)
indexes.update(ud["indexes"])
else:
else:
parser = AtomSelectionParser(trajConfig["instance"])
indexes.update(parser.parse(v))
self["flatten_indexes"] = sorted(list(indexes))
trajConfig = self._configurable[self._dependencies['trajectory']]
atoms = sorted(trajConfig["universe"].atomList(), key = operator.attrgetter('index'))
selectedAtoms = [atoms[idx] for idx in indexes]
self["selection_length"] = len(self["flatten_indexes"])
self["selection_length"] = len(self["flatten_indexes"])
self['indexes'] = [[idx] for idx in self["flatten_indexes"]]
self['elements'] = [[at.symbol] for at in selectedAtoms]
self['names'] = [at.symbol for at in selectedAtoms]
self['unique_names'] = sorted(set(self['names']))
self['masses'] = [[ELEMENTS[n,'atomic_weight']] for n in self['names']]
def get_natoms(self):
nAtomsPerElement = {}
for v in self["names"]:
if nAtomsPerElement.has_key(v):
nAtomsPerElement[v] += 1
else:
nAtomsPerElement[v] = 1
return nAtomsPerElement
def get_indexes(self):
indexesPerElement = {}
......@@ -139,9 +133,9 @@ class AtomSelectionConfigurator(IConfigurator):
indexesPerElement[v].extend(self['indexes'][i])
else:
indexesPerElement[v] = self['indexes'][i][:]
return indexesPerElement
def get_information(self):
'''
Returns some informations the atom selection.
......@@ -152,11 +146,11 @@ class AtomSelectionConfigurator(IConfigurator):
if not self.has_key("selection_length"):
return "Not configured yet\n"
info = []
info.append("Number of selected atoms:%d" % self["selection_length"])
info.append("Selected elements:%s" % self["unique_names"])
return "\n".join(info)
REGISTRY["atom_selection"] = AtomSelectionConfigurator
......@@ -121,7 +121,7 @@ class CoordinationNumber(DistanceHistogram):
cBeta = self._concentrations[pair[1]]
invPair = pair[::-1]
print pair, cnIntra
self._outputData["cn_intra_%s%s" % pair][:] = self.averageDensity*cBeta*cnIntra
self._outputData["cn_inter_%s%s" % pair][:] = self.averageDensity*cBeta*cnInter
self._outputData["cn_total_%s%s" % pair][:] = self.averageDensity*cBeta*cnTotal
......
#!python
#!/usr/bin/env python
import cPickle
import glob
......
#!python
#!/usr/bin/env python
if __name__ == "__main__":
......@@ -6,4 +6,4 @@ if __name__ == "__main__":
app = ElementsDatabaseEditorApp(None)
app.MainLoop()
\ No newline at end of file
#!python
#!/usr/bin/env python
if __name__ == "__main__":
......
#!python
#!/usr/bin/env python
if __name__ == "__main__":
......@@ -6,4 +6,4 @@ if __name__ == "__main__":
app = PeriodicTableViewerApp(None)
app.MainLoop()
\ No newline at end of file
#!python
#!/usr/bin/env python
if __name__ == "__main__":
......@@ -6,4 +6,4 @@ if __name__ == "__main__":
app = PlotterApp()
app.MainLoop()
\ No newline at end of file
#!python
#!/usr/bin/env python
if __name__ == "__main__":
......@@ -6,4 +6,4 @@ if __name__ == "__main__":
app = UserDefinitionViewerApp(None)
app.MainLoop()
\ No newline at end of file
......@@ -38,10 +38,9 @@ class JobFileGenerator():
# parameters (dict): optional. If not None, the parameters which the job file will be built with.
"""
array_of_python_dependancies_string = ['unittest', 'numpy', 'os']
array_of_mdanse_dependancies_string = ['from Tests.UnitTests.UnitTest import UnitTest',
'from MDANSE import REGISTRY']
array_of_mdanse_dependancies_string = ['from MDANSE import REGISTRY']
test_string = ''
test_string = test_string + 'class Test%s(UnitTest):\n\n' % self.job._type.upper()
test_string = test_string + 'class Test%s(unittest.TestCase):\n\n' % self.job._type.upper()
test_string = test_string + ' def test(self):\n'
# Writes the line that will initialize the |parameters| dictionary and create the job
if parameters is None:
......@@ -56,14 +55,14 @@ class JobFileGenerator():
# Launch the job in monoprocessor mode and copy output file
test_string = test_string + ' print "Launching job in monoprocessor mode"\n'
test_string = test_string + ' parameters["running_mode"] = ("monoprocessor",1)\n'
test_string = test_string + ' self.assertNotRaises(job.run, parameters, status=False)\n'
test_string = test_string + ' job.run(parameters, status=False)\n'
test_string = test_string + ' shutil.copy(output_path + ".nc", reference_data_path + "_mono" + ".nc")\n'
test_string = test_string + ' print "Monoprocessor execution completed"\n\n'
# Launch the job in multiprocessor mode if avalaible
if self.multiprocessor:
test_string = test_string + ' print "Launching job in multiprocessor mode"\n'
test_string = test_string + ' parameters["running_mode"] = ("multiprocessor",2)\n'
test_string = test_string + ' self.assertNotRaises(job.run,parameters,False)\n'
test_string = test_string + ' job.run(parameters,False)\n'
test_string = test_string + ' shutil.copy(output_path + ".nc", reference_data_path + "_multi" + ".nc")\n'
test_string = test_string + ' print "Multiprocessor execution completed"\n\n'
# Compare reference data with monoprocessor if reference data exists
......
......@@ -41,11 +41,10 @@ from MDANSE.Framework.Configurable import Configurable
from MDANSE.Framework.Configurators.IConfigurator import ConfiguratorError
from MDANSE.Framework.Projectors.IProjector import ProjectorError
from MDANSE.Framework.AtomSelectionParser import AtomSelectionParserError
from UnitTest import UnitTest
TRAJECTORIES_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),"UserData","Trajectories")
class TestConfigurator(UnitTest):
class TestConfigurator(unittest.TestCase):
'''
Unittest for the configurators used to setup an analysis in MDANSE
'''
......@@ -70,16 +69,16 @@ class TestConfigurator(UnitTest):
# Case of a valid integer
self._parameters["test_integer"] = 20
self.assertNotRaises(self._configurable.setup,self._parameters)
self._configurable.setup(self._parameters)
# Case of a float that will casted to an integer
self._parameters["test_integer"] = 20.2
self.assertNotRaises(self._configurable.setup,self._parameters)
self._configurable.setup(self._parameters)
self.assertEqual(self._configurable["test_integer"]["value"], 20)
# Case of a string that can be casted to an integer
self._parameters["test_integer"] = "30"
self.assertNotRaises(self._configurable.setup,self._parameters)
self._configurable.setup(self._parameters)
self.assertEqual(self._configurable["test_integer"]["value"], 30)
# Case of a string that cannot be casted to an integer
......@@ -99,17 +98,17 @@ class TestConfigurator(UnitTest):
# Case of an integer that will be casted to a float
self._parameters["test_float"] = 20
self.assertNotRaises(self._configurable.setup,self._parameters)
self._configurable.setup(self._parameters)
self.assertEqual(self._configurable["test_float"]["value"], 20.0)
# Case of a float
self._parameters["test_float"] = 20.2
self.assertNotRaises(self._configurable.setup,self._parameters)
self._configurable.setup(self._parameters)
self.assertEqual(self._configurable["test_float"]["value"], 20.2)
# Case of a string that can be casted to a float
self._parameters["test_float"] = "30.2"
self.assertNotRaises(self._configurable.setup,self._parameters)
self._configurable.setup(self._parameters)
self.assertEqual(self._configurable["test_float"]["value"], 30.2)
# Case of a string that cannot be casted to a float
......@@ -129,7 +128,7 @@ class TestConfigurator(UnitTest):
# Case of a valid trajectory
self._parameters["trajectory"] = self._validTrajectory.filename
self.assertNotRaises(self._configurable.setup,self._parameters)
self._configurable.setup(self._parameters)
# Case of an unknown trajectory
self._parameters["trajectory"] = 'fsfsdjkfjkfjs'
......@@ -162,12 +161,12 @@ class TestConfigurator(UnitTest):
# No projection
self._parameters["projection"] = None
self.assertNotRaises(self._configurable.setup,self._parameters)
self._configurable.setup(self._parameters)
proj = self._configurable["projection"]['projector'](data)
self.assertTrue(numpy.array_equal(data,proj))
self._parameters["projection"] = ('null',None)
self.assertNotRaises(self._configurable.setup,self._parameters)
self._configurable.setup(self._parameters)
proj = self._configurable["projection"]['projector'](data)
self.assertTrue(numpy.array_equal(data,proj))
......@@ -185,13 +184,13 @@ class TestConfigurator(UnitTest):
# Axial projection
self._parameters["projection"] = ('axial',(1,0,0))
self.assertNotRaises(self._configurable.setup,self._parameters)
self._configurable.setup(self._parameters)
proj = self._configurable["projection"]['projector'](data)
self.assertTrue(numpy.array_equal(data[:,0],proj[:,0]))
# Axial projection - wrong data
self._parameters["projection"] = ('axial',(1,0,0))
self.assertNotRaises(self._configurable.setup,self._parameters)
self._configurable.setup(self._parameters)
self.assertRaises(ProjectorError, self._configurable["projection"]['projector'].__call__,None)
self.assertRaises(ProjectorError, self._configurable["projection"]['projector'].__call__,[1])
......@@ -209,7 +208,7 @@ class TestConfigurator(UnitTest):
# Planar projection
self._parameters["projection"] = ('planar',(1,0,0))
self.assertNotRaises(self._configurable.setup,self._parameters)
self._configurable.setup(self._parameters)
proj = self._configurable["projection"]['projector'](data)
self.assertTrue(numpy.array_equal(numpy.zeros((data.shape[0],), dtype=numpy.float64),proj[:,0]))
self.assertTrue(numpy.array_equal(data[:,1],proj[:,1]))
......@@ -217,7 +216,7 @@ class TestConfigurator(UnitTest):
# Planar projection - wrong data
self._parameters["projection"] = ('planar',(1,0,0))
self.assertNotRaises(self._configurable.setup,self._parameters)
self._configurable.setup(self._parameters)
self.assertRaises(ProjectorError, self._configurable["projection"]['projector'].__call__,None)
self.assertRaises(ProjectorError, self._configurable["projection"]['projector'].__call__,[1])
......@@ -255,7 +254,7 @@ class TestConfigurator(UnitTest):
# Test a valid atom selection string
self._parameters["trajectory"] = self._validTrajectory.filename
self._parameters["atom_selection"] = 'atom_type carbon'
self.assertNotRaises(self._configurable.setup,self._parameters)
self._configurable.setup(self._parameters)
self.assertEqual(self._configurable['atom_selection']['selection_length'],sum([True for at in self._configurable['trajectory']['instance'].universe.atomList() if at.symbol=='C']))
def test_atom_transmutation(self):
......@@ -289,7 +288,7 @@ class TestConfigurator(UnitTest):
# Test a valid atom selection string
self._parameters["trajectory"] = self._validTrajectory.filename
self._parameters["atom_transmutation"] = None
self.assertNotRaises(self._configurable.setup,self._parameters)
self._configurable.setup(self._parameters)
def suite():
loader = unittest.TestLoader()
......
......@@ -32,12 +32,10 @@ Created on May 29, 2015
import unittest
from UnitTest import UnitTest
from MDANSE import ELEMENTS
from MDANSE.Data.ElementsDatabase import ElementsDatabaseError
class TestElementsDatabase(UnitTest):
class TestElementsDatabase(unittest.TestCase):
'''
Unittest for the configurators used to setup an analysis in MDANSE
'''
......@@ -57,26 +55,26 @@ class TestElementsDatabase(UnitTest):
for e in ELEMENTS.elements:
for p in ELEMENTS.properties:
self.assertNotRaises(ELEMENTS.__getitem__,(e,p))
_ = ELEMENTS[e,p]
def test_getelement(self):
for e in ELEMENTS.elements:
self.assertNotRaises(ELEMENTS.get_element,e)
_ = ELEMENTS.get_element(e)
def test_get_property(self):
for p in ELEMENTS.properties:
self.assertNotRaises(ELEMENTS.get_property,p)
_ = ELEMENTS.get_property(p)
def test___setitem__(self):
self.assertNotRaises(ELEMENTS.__setitem__,('C','atomic_weight'),20.0)
ELEMENTS['C','atomic_weight'] = 20.0
def test_add_element(self):
# Otherwise, everything should be OK
self.assertNotRaises(ELEMENTS.add_element, "element1")
ELEMENTS.add_element("element1")
def test_add_property(self):
......@@ -84,9 +82,9 @@ class TestElementsDatabase(UnitTest):
self.assertRaises(ElementsDatabaseError, ELEMENTS.add_property, "atomic_weight",0.0)
# Otherwise, everything should be OK
self.assertNotRaises(ELEMENTS.add_property, "prop1",'float')
self.assertNotRaises(ELEMENTS.add_property, "prop2",'int')
self.assertNotRaises(ELEMENTS.add_property, "prop3",'str')
ELEMENTS.add_property("prop1",'float')
ELEMENTS.add_property("prop2",'int')
ELEMENTS.add_property("prop3",'str')
def test_has_property(self):
......@@ -111,4 +109,4 @@ def suite():
if __name__ == '__main__':
unittest.main(verbosity=2)
\ No newline at end of file
......@@ -34,11 +34,9 @@ import unittest
import numpy
from UnitTest import UnitTest
from MDANSE.Mathematics.Geometry import center_of_mass
class TestGeometry(UnitTest):
class TestGeometry(unittest.TestCase):
'''
Unittest for the geometry-related functions
'''
......@@ -62,4 +60,4 @@ def suite():
if __name__ == '__main__':
unittest.main(verbosity=2)
\ No newline at end of file
......@@ -34,11 +34,9 @@ import unittest
import numpy
from UnitTest import UnitTest
from MDANSE.MolecularDynamics.Analysis import radius_of_gyration, mean_square_deviation, mean_square_fluctuation
class TestMolecularDynamics(UnitTest):
class TestMolecularDynamics(unittest.TestCase):
'''
Unittest for the geometry-related functions
'''
......@@ -76,4 +74,4 @@ def suite():
if __name__ == '__main__':
unittest.main(verbosity=2)
\ No newline at end of file
#MDANSE : Molecular Dynamics Analysis for Neutron Scattering Experiments
#------------------------------------------------------------------------------------------
#Copyright (C)
#2015- Eric C. Pellegrini Institut Laue-Langevin
#BP 156
#6, rue Jules Horowitz
#38042 Grenoble Cedex 9
#France
#pellegrini[at]ill.fr
#goret[at]ill.fr
#aoun[at]ill.fr
#
#This library is free software; you can redistribute it and/or
#modify it under the terms of the GNU Lesser General Public
#License as published by the Free Software Foundation; either
#version 2.1 of the License, or (at your option) any later version.
#
#This library is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
#Lesser General Public License for more details.
#
#You should have received a copy of the GNU Lesser General Public
#License along with this library; if not, write to the Free Software
#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
'''
Created on May 29, 2015
@author: Eric C. Pellegrini
'''
import sys
import unittest
class UnitTest(unittest.TestCase):
def assertNotRaises(self, callableObj, *args, **kwargs):
try:
callableObj(*args, **kwargs)
except:
self.fail(sys.exc_info())
import fnmatch
import glob
import os
import subprocess
import sys
import numpy
......@@ -168,52 +169,55 @@ SCRIPTS = glob.glob(os.path.join(SCRIPTS_PATH,'mdanse*'))
#################################
if sphinx:
import sphinx.apidoc
import sphinx.setup_command
try:
from sphinx.ext.apidoc import main as sphinx_apidoc_main