<commit_before>#***************************************************************************
#*                                                                         *
#*   Copyright (c) 2013 - Juergen Riegel <FreeCAD@juergen-riegel.net>      *
#*                                                                         *
#*   This program is free software; you can redistribute it and/or modify  *
#*   it under the terms of the GNU Lesser General Public License (LGPL)    *
#*   as published by the Free Software Foundation; either version 2 of     *
#*   the License, or (at your option) any later version.                   *
#*   for detail see the LICENCE text file.                                 *
#*                                                                         *
#*   This program 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 Library General Public License for more details.                  *
#*                                                                         *
#*   You should have received a copy of the GNU Library General Public     *
#*   License along with this program; if not, write to the Free Software   *
#*   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *
#*   USA                                                                   *
#*                                                                         *
#***************************************************************************

import FreeCAD

if FreeCAD.GuiUp:
    import FreeCADGui
    import FemGui
    from PySide import QtCore, QtGui

__title__="Machine-Distortion FemSetGeometryObject managment"
__author__ = "Juergen Riegel"
__url__ = "http://www.freecadweb.org"

def makeMechanicalMaterial(name):
    '''makeMaterial(name): makes an Material
    name there fore is a material name or an file name for a FCMat file'''
    obj = FreeCAD.ActiveDocument.addObject("App::MaterialObjectPython",name)
    _MechanicalMaterial(obj)
    _ViewProviderMechanicalMaterial(obj.ViewObject)
    #FreeCAD.ActiveDocument.recompute()
    return obj

class _CommandMechanicalMaterial:
    "the Fem Material command definition"
    def GetResources(self):
        return {'Pixmap'  : 'Fem_Material',
                'MenuText': QtCore.QT_TRANSLATE_NOOP("Fem_Material","Mechanical material..."),
                'Accel': "A, X",
                'ToolTip': QtCore.QT_TRANSLATE_NOOP("Fem_Material","Creates or edit the mechanical material definition.")}

    def Activated(self):
        MatObj = None
        for i in FemGui.getActiveAnalysis().Member:
            if i.isDerivedFrom("App::MaterialObject"):
                    MatObj = i

        if (not MatObj):
            FreeCAD.ActiveDocument.openTransaction("Create Material")
            FreeCADGui.addModule("MechanicalMaterial")
            FreeCADGui.doCommand("MechanicalMaterial.makeMechanicalMaterial('MechanicalMaterial')")
            FreeCADGui.doCommand("App.activeDocument()."+FemGui.getActiveAnalysis().Name+".Member = App.activeDocument()."+FemGui.getActiveAnalysis().Name+".Member + [App.ActiveDocument.ActiveObject]")
            FreeCADGui.doCommand("Gui.activeDocument().setEdit(App.ActiveDocument.ActiveObject.Name,0)")
            #FreeCADGui.doCommand("Fem.makeMaterial()")
        else:
            FreeCADGui.doCommand("Gui.activeDocument().setEdit('"+MatObj.Name+"',0)")

    def IsActive(self):
        if FemGui.getActiveAnalysis():
            return True
        else:
            return False

class _MechanicalMaterial:
    "The Material object"
    def __init__(self,obj):
        self.Type = "MechanicaltMaterial"
        obj.Proxy = self
        #obj.Material = StartMat

    def execute(self,obj):
        return

class _ViewProviderMechanicalMaterial:
    "A View Provider for the MechanicalMaterial object"

    def __init__(self,vobj):
        vobj.Proxy = self

    def getIcon(self):
        return ":/icons/Fem_Material.svg"

    def attach(self, vobj):
        self.ViewObject = vobj
        self.Object = vobj.Object

    def updateData(self, obj, prop):
        return

    def onChanged(self, vobj, prop):
        return

    def setEdit(self,vobj,mode):
        taskd = _MechanicalMaterialTaskPanel(self.Object)
        taskd.obj = vobj.Object
        taskd.update()
        FreeCADGui.Control.showDialog(taskd)
        return True

    def unsetEdit(self,vobj,mode):
        FreeCADGui.Control.closeDialog()
        return

    def __getstate__(self):
        return None

    def __setstate__(self,state):
        return None

class _MechanicalMaterialTaskPanel:
    '''The editmode TaskPanel for MechanicalMaterial objects'''
    def __init__(self,obj):
        self.obj = obj

        self.form=FreeCADGui.PySideUic.loadUi(FreeCAD.getHomePath() + "Mod/Fem/MechanicalMaterial.ui")
        self.params = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Fem")

        QtCore.QObject.connect(self.form.pushButton_MatWeb, QtCore.SIGNAL("clicked()"), self.goMatWeb)
        QtCore.QObject.connect(self.form.comboBox_MaterialsInDir, QtCore.SIGNAL("currentIndexChanged(int)"), self.chooseMat)

        self.update()

    def transferTo(self):
        "Transfer from the dialog to the object"

        matmap = self.obj.Material

        matmap['Mechanical_youngsmodulus']       = self.form.spinBox_young_modulus.text()
        matmap['FEM_poissonratio']   = str(self.form.spinBox_poisson_ratio.value())
        print self.form.comboBox_MaterialsInDir.currentText()

        self.obj.Material = matmap
        print 'material data:'
        if matmap.has_key('General_name'):
            print ' Name = ', matmap['General_name']
        if matmap.has_key('Mechanical_youngsmodulus'):
            print ' YM = ', matmap['Mechanical_youngsmodulus']
        if matmap.has_key('FEM_poissonratio'):
            print ' PR = ', matmap['FEM_poissonratio']

    def transferFrom(self):
        "Transfer from the object to the dialog"
        matmap = self.obj.Material

        if matmap.has_key('Mechanical_youngsmodulus'):
            #print matmap['Mechanical_youngsmodulus']
            self.form.spinBox_young_modulus.setText(matmap['Mechanical_youngsmodulus'])
        if matmap.has_key('FEM_poissonratio'):
            #print float(matmap['FEM_poissonratio'])
            self.form.spinBox_poisson_ratio.setValue(float(matmap['FEM_poissonratio']))

    def isAllowedAlterSelection(self):
        return False

    def isAllowedAlterView(self):
        return True

    def getStandardButtons(self):
        return int(QtGui.QDialogButtonBox.Ok) | int(QtGui.QDialogButtonBox.Cancel)

    def update(self):
        'fills the widgets'
        #self.form.spinBox_young_modulus.setValue(0.0)
        #self.form.spinBox_poisson_ratio.setValue(0.0)
        self.transferFrom()
        self.fillMaterialCombo()

        return

    def accept(self):
        #print 'accept(self)'
        self.transferTo()
        FreeCADGui.ActiveDocument.resetEdit()

    def reject(self):
        #print 'reject(self)'
        matmap = self.obj.Material
        print 'material data:'
        if matmap.has_key('General_name'):
            print ' Name = ', matmap['General_name']
        if matmap.has_key('Mechanical_youngsmodulus'):
            print ' YM = ', matmap['Mechanical_youngsmodulus']
        if matmap.has_key('FEM_poissonratio'):
            print ' PR = ', matmap['FEM_poissonratio']
        FreeCADGui.ActiveDocument.resetEdit()

    def saveMat(self):
        self.transferTo()
        filename = QtGui.QFileDialog.getSaveFileName(None, 'Save Material file file',self.params.GetString("MaterialDir",'/'),'FreeCAD material file (*.FCMat)')
        if(filename):
            import Material
            Material.exportFCMat(filename,self.obj.Material)

    def goMatWeb(self):
        import webbrowser
        webbrowser.open("http://matweb.com")

    def chooseMat(self,index):
        if index <= 0:
            return
        import Material
        #print index
        name = self.pathList[index - 1]
        #print 'Import ', str(name)

        self.obj.Material = Material.importFCMat(str(name))
        #print self.obj.Material

        self.transferFrom()

    def fillMaterialCombo(self):
        import glob
        import os
        matmap = self.obj.Material
        dirname =  FreeCAD.getResourceDir()+"/Mod/Material/StandardMaterial"
        self.pathList = glob.glob(dirname + '/*.FCMat')
        self.form.comboBox_MaterialsInDir.clear()
        '''if(matmap.has_key('General_name')):
            self.form.comboBox_MaterialsInDir.addItem(matmap['General_name'])
        else:
            self.form.comboBox_MaterialsInDir.addItem('-> choose Material')
        '''
        # workaraound: since material data is not loaded into spinBoxes the user has
        # to choose the material every time the MechanincalMaterialWidget is opened
        self.form.comboBox_MaterialsInDir.addItem('-> choose Material')
        for i in self.pathList:
            self.form.comboBox_MaterialsInDir.addItem(os.path.basename(i))

FreeCADGui.addCommand('Fem_MechanicalMaterial',_CommandMechanicalMaterial())
<commit_msg>FEM: Fix spaces around =/+/: and brackets<commit_after>#***************************************************************************
#*                                                                         *
#*   Copyright (c) 2013 - Juergen Riegel <FreeCAD@juergen-riegel.net>      *
#*                                                                         *
#*   This program is free software; you can redistribute it and/or modify  *
#*   it under the terms of the GNU Lesser General Public License (LGPL)    *
#*   as published by the Free Software Foundation; either version 2 of     *
#*   the License, or (at your option) any later version.                   *
#*   for detail see the LICENCE text file.                                 *
#*                                                                         *
#*   This program 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 Library General Public License for more details.                  *
#*                                                                         *
#*   You should have received a copy of the GNU Library General Public     *
#*   License along with this program; if not, write to the Free Software   *
#*   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *
#*   USA                                                                   *
#*                                                                         *
#***************************************************************************

import FreeCAD

if FreeCAD.GuiUp:
    import FreeCADGui
    import FemGui
    from PySide import QtCore, QtGui

__title__ = "Machine-Distortion FemSetGeometryObject managment"
__author__ = "Juergen Riegel"
__url__ = "http://www.freecadweb.org"

def makeMechanicalMaterial(name):
    '''makeMaterial(name): makes an Material
    name there fore is a material name or an file name for a FCMat file'''
    obj = FreeCAD.ActiveDocument.addObject("App::MaterialObjectPython",name)
    _MechanicalMaterial(obj)
    _ViewProviderMechanicalMaterial(obj.ViewObject)
    #FreeCAD.ActiveDocument.recompute()
    return obj

class _CommandMechanicalMaterial:
    "the Fem Material command definition"
    def GetResources(self):
        return {'Pixmap': 'Fem_Material',
                'MenuText': QtCore.QT_TRANSLATE_NOOP("Fem_Material","Mechanical material..."),
                'Accel': "A, X",
                'ToolTip': QtCore.QT_TRANSLATE_NOOP("Fem_Material","Creates or edit the mechanical material definition.")}

    def Activated(self):
        MatObj = None
        for i in FemGui.getActiveAnalysis().Member:
            if i.isDerivedFrom("App::MaterialObject"):
                    MatObj = i

        if (not MatObj):
            FreeCAD.ActiveDocument.openTransaction("Create Material")
            FreeCADGui.addModule("MechanicalMaterial")
            FreeCADGui.doCommand("MechanicalMaterial.makeMechanicalMaterial('MechanicalMaterial')")
            FreeCADGui.doCommand("App.activeDocument()." + FemGui.getActiveAnalysis().Name + ".Member = App.activeDocument()." + FemGui.getActiveAnalysis().Name + ".Member + [App.ActiveDocument.ActiveObject]")
            FreeCADGui.doCommand("Gui.activeDocument().setEdit(App.ActiveDocument.ActiveObject.Name,0)")
            #FreeCADGui.doCommand("Fem.makeMaterial()")
        else:
            FreeCADGui.doCommand("Gui.activeDocument().setEdit('" + MatObj.Name + "',0)")

    def IsActive(self):
        if FemGui.getActiveAnalysis():
            return True
        else:
            return False

class _MechanicalMaterial:
    "The Material object"
    def __init__(self,obj):
        self.Type = "MechanicaltMaterial"
        obj.Proxy = self
        #obj.Material = StartMat

    def execute(self,obj):
        return

class _ViewProviderMechanicalMaterial:
    "A View Provider for the MechanicalMaterial object"

    def __init__(self,vobj):
        vobj.Proxy = self

    def getIcon(self):
        return ":/icons/Fem_Material.svg"

    def attach(self, vobj):
        self.ViewObject = vobj
        self.Object = vobj.Object

    def updateData(self, obj, prop):
        return

    def onChanged(self, vobj, prop):
        return

    def setEdit(self,vobj,mode):
        taskd = _MechanicalMaterialTaskPanel(self.Object)
        taskd.obj = vobj.Object
        taskd.update()
        FreeCADGui.Control.showDialog(taskd)
        return True

    def unsetEdit(self,vobj,mode):
        FreeCADGui.Control.closeDialog()
        return

    def __getstate__(self):
        return None

    def __setstate__(self,state):
        return None

class _MechanicalMaterialTaskPanel:
    '''The editmode TaskPanel for MechanicalMaterial objects'''
    def __init__(self,obj):
        self.obj = obj

        self.form = FreeCADGui.PySideUic.loadUi(FreeCAD.getHomePath() + "Mod/Fem/MechanicalMaterial.ui")
        self.params = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Fem")

        QtCore.QObject.connect(self.form.pushButton_MatWeb, QtCore.SIGNAL("clicked()"), self.goMatWeb)
        QtCore.QObject.connect(self.form.comboBox_MaterialsInDir, QtCore.SIGNAL("currentIndexChanged(int)"), self.chooseMat)

        self.update()

    def transferTo(self):
        "Transfer from the dialog to the object"

        matmap = self.obj.Material

        matmap['Mechanical_youngsmodulus'] = self.form.spinBox_young_modulus.text()
        matmap['FEM_poissonratio'] = str(self.form.spinBox_poisson_ratio.value())
        print self.form.comboBox_MaterialsInDir.currentText()

        self.obj.Material = matmap
        print 'material data:'
        if matmap.has_key('General_name'):
            print ' Name = ', matmap['General_name']
        if matmap.has_key('Mechanical_youngsmodulus'):
            print ' YM = ', matmap['Mechanical_youngsmodulus']
        if matmap.has_key('FEM_poissonratio'):
            print ' PR = ', matmap['FEM_poissonratio']

    def transferFrom(self):
        "Transfer from the object to the dialog"
        matmap = self.obj.Material

        if matmap.has_key('Mechanical_youngsmodulus'):
            #print matmap['Mechanical_youngsmodulus']
            self.form.spinBox_young_modulus.setText(matmap['Mechanical_youngsmodulus'])
        if matmap.has_key('FEM_poissonratio'):
            #print float(matmap['FEM_poissonratio'])
            self.form.spinBox_poisson_ratio.setValue(float(matmap['FEM_poissonratio']))

    def isAllowedAlterSelection(self):
        return False

    def isAllowedAlterView(self):
        return True

    def getStandardButtons(self):
        return int(QtGui.QDialogButtonBox.Ok) | int(QtGui.QDialogButtonBox.Cancel)

    def update(self):
        'fills the widgets'
        #self.form.spinBox_young_modulus.setValue(0.0)
        #self.form.spinBox_poisson_ratio.setValue(0.0)
        self.transferFrom()
        self.fillMaterialCombo()

        return

    def accept(self):
        #print 'accept(self)'
        self.transferTo()
        FreeCADGui.ActiveDocument.resetEdit()

    def reject(self):
        #print 'reject(self)'
        matmap = self.obj.Material
        print 'material data:'
        if matmap.has_key('General_name'):
            print ' Name = ', matmap['General_name']
        if matmap.has_key('Mechanical_youngsmodulus'):
            print ' YM = ', matmap['Mechanical_youngsmodulus']
        if matmap.has_key('FEM_poissonratio'):
            print ' PR = ', matmap['FEM_poissonratio']
        FreeCADGui.ActiveDocument.resetEdit()

    def saveMat(self):
        self.transferTo()
        filename = QtGui.QFileDialog.getSaveFileName(None, 'Save Material file file',self.params.GetString("MaterialDir",'/'),'FreeCAD material file (*.FCMat)')
        if(filename):
            import Material
            Material.exportFCMat(filename,self.obj.Material)

    def goMatWeb(self):
        import webbrowser
        webbrowser.open("http://matweb.com")

    def chooseMat(self,index):
        if index <= 0:
            return
        import Material
        #print index
        name = self.pathList[index - 1]
        #print 'Import ', str(name)

        self.obj.Material = Material.importFCMat(str(name))
        #print self.obj.Material

        self.transferFrom()

    def fillMaterialCombo(self):
        import glob
        import os
        matmap = self.obj.Material
        dirname =  FreeCAD.getResourceDir()+"/Mod/Material/StandardMaterial"
        self.pathList = glob.glob(dirname + '/*.FCMat')
        self.form.comboBox_MaterialsInDir.clear()
        '''if(matmap.has_key('General_name')):
            self.form.comboBox_MaterialsInDir.addItem(matmap['General_name'])
        else:
            self.form.comboBox_MaterialsInDir.addItem('-> choose Material')
        '''
        # workaraound: since material data is not loaded into spinBoxes the user has
        # to choose the material every time the MechanincalMaterialWidget is opened
        self.form.comboBox_MaterialsInDir.addItem('-> choose Material')
        for i in self.pathList:
            self.form.comboBox_MaterialsInDir.addItem(os.path.basename(i))

FreeCADGui.addCommand('Fem_MechanicalMaterial',_CommandMechanicalMaterial())
<|endoftext|>


<commit_before># ***************************************************************************
# *   Copyright (c) 2015 - FreeCAD Developers                               *
# *   Author: Bernd Hahnebach <bernd@bimstatik.org>                         *
# *                                                                         *
# *   This file is part of the FreeCAD CAx development system.              *
# *                                                                         *
# *   This program is free software; you can redistribute it and/or modify  *
# *   it under the terms of the GNU Lesser General Public License (LGPL)    *
# *   as published by the Free Software Foundation; either version 2 of     *
# *   the License, or (at your option) any later version.                   *
# *   for detail see the LICENCE text file.                                 *
# *                                                                         *
# *   FreeCAD 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 Library General Public License for more details.                  *
# *                                                                         *
# *   You should have received a copy of the GNU Library General Public     *
# *   License along with FreeCAD; if not, write to the Free Software        *
# *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *
# *   USA                                                                   *
# *                                                                         *
# ***************************************************************************/

import FreeCAD
import ObjectsFem
import unittest
from . import utilstest as testtools
from .utilstest import fcc_print

from os.path import join

class TestFemCommon(unittest.TestCase):
    fcc_print('import TestFemCommon')

    def setUp(self):
        # init, is executed before every test
        self.doc_name = "TestsFemCommon"
        try:
            FreeCAD.setActiveDocument(self.doc_name)
        except:
            FreeCAD.newDocument(self.doc_name)
        finally:
            FreeCAD.setActiveDocument(self.doc_name)
        self.active_doc = FreeCAD.ActiveDocument

    def test_adding_refshaps(self):
        doc = self.active_doc
        slab = doc.addObject("Part::Plane", "Face")
        slab.Length = 500.00
        slab.Width = 500.00
        cf = ObjectsFem.makeConstraintFixed(doc)
        ref_eles = []
        # FreeCAD list property seam not to support append, thus we need some workaround, which is on many elements even much faster
        for i, face in enumerate(slab.Shape.Edges):
            ref_eles.append("Edge%d" % (i + 1))
        cf.References = [(slab, ref_eles)]
        doc.recompute()
        expected_reflist = [(slab, ('Edge1', 'Edge2', 'Edge3', 'Edge4'))]
        assert_err_message = 'Adding reference shapes did not result in expected list ' + str(cf.References) + ' != ' + str(expected_reflist)
        self.assertEqual(cf.References, expected_reflist, assert_err_message)

    def test_pyimport_all_FEM_modules(self):
        # we're going to try to import all python modules from FreeCAD Fem
        pymodules = []

        # collect all Python modules in Fem
        pymodules += testtools.collect_python_modules('')  # Fem main dir
        pymodules += testtools.collect_python_modules('feminout')
        pymodules += testtools.collect_python_modules('femmesh')
        pymodules += testtools.collect_python_modules('femresult')
        pymodules += testtools.collect_python_modules('femtest')
        pymodules += testtools.collect_python_modules('femobjects')
        if FreeCAD.GuiUp:
            pymodules += testtools.collect_python_modules('femcommands')
            pymodules += testtools.collect_python_modules('femguiobjects')
        pymodules += testtools.collect_python_modules('femsolver')
        pymodules += testtools.collect_python_modules(join('femsolver', 'elmer'))
        pymodules += testtools.collect_python_modules(join('femsolver', 'elmer', 'equations'))
        pymodules += testtools.collect_python_modules(join('femsolver', 'z88'))
        pymodules += testtools.collect_python_modules(join('femsolver', 'calculix'))

        # import all collected modules
        # fcc_print(pymodules)
        for mod in pymodules:
            fcc_print('Try importing {0} ...'.format(mod))
            try:
                im = __import__('{0}'.format(mod))
            except:
                im = False
            if not im:
                __import__('{0}'.format(mod))  # to get an error message what was going wrong
            self.assertTrue(im, 'Problem importing {0}'.format(mod))

    def tearDown(self):
        # clearance, is executed after every test
        FreeCAD.closeDocument(self.doc_name)
        pass
<commit_msg>FEM: unit tests, do not use join on module import test<commit_after># ***************************************************************************
# *   Copyright (c) 2015 - FreeCAD Developers                               *
# *   Author: Bernd Hahnebach <bernd@bimstatik.org>                         *
# *                                                                         *
# *   This file is part of the FreeCAD CAx development system.              *
# *                                                                         *
# *   This program is free software; you can redistribute it and/or modify  *
# *   it under the terms of the GNU Lesser General Public License (LGPL)    *
# *   as published by the Free Software Foundation; either version 2 of     *
# *   the License, or (at your option) any later version.                   *
# *   for detail see the LICENCE text file.                                 *
# *                                                                         *
# *   FreeCAD 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 Library General Public License for more details.                  *
# *                                                                         *
# *   You should have received a copy of the GNU Library General Public     *
# *   License along with FreeCAD; if not, write to the Free Software        *
# *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *
# *   USA                                                                   *
# *                                                                         *
# ***************************************************************************/

import FreeCAD
import ObjectsFem
import unittest
from . import utilstest as testtools
from .utilstest import fcc_print

from os.path import join

class TestFemCommon(unittest.TestCase):
    fcc_print('import TestFemCommon')

    def setUp(self):
        # init, is executed before every test
        self.doc_name = "TestsFemCommon"
        try:
            FreeCAD.setActiveDocument(self.doc_name)
        except:
            FreeCAD.newDocument(self.doc_name)
        finally:
            FreeCAD.setActiveDocument(self.doc_name)
        self.active_doc = FreeCAD.ActiveDocument

    def test_adding_refshaps(self):
        doc = self.active_doc
        slab = doc.addObject("Part::Plane", "Face")
        slab.Length = 500.00
        slab.Width = 500.00
        cf = ObjectsFem.makeConstraintFixed(doc)
        ref_eles = []
        # FreeCAD list property seam not to support append, thus we need some workaround, which is on many elements even much faster
        for i, face in enumerate(slab.Shape.Edges):
            ref_eles.append("Edge%d" % (i + 1))
        cf.References = [(slab, ref_eles)]
        doc.recompute()
        expected_reflist = [(slab, ('Edge1', 'Edge2', 'Edge3', 'Edge4'))]
        assert_err_message = 'Adding reference shapes did not result in expected list ' + str(cf.References) + ' != ' + str(expected_reflist)
        self.assertEqual(cf.References, expected_reflist, assert_err_message)

    def test_pyimport_all_FEM_modules(self):
        # we're going to try to import all python modules from FreeCAD Fem
        pymodules = []

        # collect all Python modules in Fem
        pymodules += testtools.collect_python_modules('')  # Fem main dir
        pymodules += testtools.collect_python_modules('femexamples')
        pymodules += testtools.collect_python_modules('feminout')
        pymodules += testtools.collect_python_modules('femmesh')
        pymodules += testtools.collect_python_modules('femobjects')
        pymodules += testtools.collect_python_modules('femresult')
        pymodules += testtools.collect_python_modules('femtest')
        pymodules += testtools.collect_python_modules('femtools')
        pymodules += testtools.collect_python_modules('femsolver')
        # TODO test with join on windows, the use of os.path.join in following code seams to make problems on windws os
        pymodules += testtools.collect_python_modules('femsolver/elmer')
        pymodules += testtools.collect_python_modules('femsolver/elmer/equations')
        pymodules += testtools.collect_python_modules('femsolver/z88')
        pymodules += testtools.collect_python_modules('femsolver/calculix')
        if FreeCAD.GuiUp:
            pymodules += testtools.collect_python_modules('femcommands')
            pymodules += testtools.collect_python_modules('femguiobjects')

        # import all collected modules
        # fcc_print(pymodules)
        for mod in pymodules:
            fcc_print('Try importing {0} ...'.format(mod))
            try:
                im = __import__('{0}'.format(mod))
            except:
                im = False
            if not im:
                __import__('{0}'.format(mod))  # to get an error message what was going wrong
            self.assertTrue(im, 'Problem importing {0}'.format(mod))

    def tearDown(self):
        # clearance, is executed after every test
        FreeCAD.closeDocument(self.doc_name)
        pass
<|endoftext|>


<commit_before># This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

import distutils.spawn
import os
import os.path
import subprocess
import traceback
import shlex

from ansible import constants as C
from ansible.compat import six
from ansible.compat.six.moves import shlex_quote
from ansible.errors import AnsibleError
from ansible.module_utils._text import to_bytes, to_text
from ansible.plugins.connection import ConnectionBase, BUFSIZE

try:
    from __main__ import display
except ImportError:
    from ansible.utils.display import Display
    display = Display()

class Connection(ConnectionBase):
    ''' Local nspawn based connections '''

    transport = 'nspawn'
    has_pipelining = True
    become_methods = frozenset(C.BECOME_METHODS)

    def __init__(self, play_context, new_stdin, *args, **kwargs):
        super(Connection, self).__init__(play_context, new_stdin,
                                         *args, **kwargs)

        display.vvv("NSPAWN ARGS %s" % self._play_context.nspawn_args)

        self.ostree = os.path.normpath(self._play_context.remote_addr)

        if os.geteuid() != 0:
            raise AnsibleError("nspawn connection requires running as root")

        # we're running as root on the local system so do some
        # trivial checks for ensuring 'host' may be an OS tree dir
        if not os.path.isdir(self.ostree):
            raise AnsibleError("%s is not a directory" % self.ostree)

        # As systemd-nspawn will, we check the existence of os-release files
        # in the container tree to think it looks like an OS tree enough
        # see man systemd-nspawn(1) and os-release(5)
        if not (
            os.path.isfile(os.path.join(self.ostree, "usr/lib/os-release"))
            or os.path.isfile(os.path.join(self.ostree, "etc/os-release"))
        ):
            raise AnsibleError("%s does not contain an os-release file"
                               % self.ostree)

        self.nspawn_cmd = distutils.spawn.find_executable('systemd-nspawn')
        if not self.nspawn_cmd:
            raise AnsibleError("systemd-nspawn command not found in PATH")

    def _connect(self):
        ''' Connect to the container. Nothing to do '''
        super(Connection, self)._connect()
        if not self._connected:
            display.vvv(u"THIS IS A LOCAL NSPAWN CONTAINER", host=self.ostree)
            self._connected = True

    def _buffered_exec_command(self, cmd, stdin=subprocess.PIPE):
        ''' run a command in the container.  This is only needed for
        implementing put_file() get_file() so that we don't have to
        read the whole file into memory.

        compared to exec_command() it looses some niceties like being
        able to return the process's exit code immediately.
        '''
        executable = (
            C.DEFAULT_EXECUTABLE.split()[0]
            if C.DEFAULT_EXECUTABLE
            else '/bin/sh')

        nspawn_args = self._play_context.nspawn_args
        if six.PY2:
            nspawn_args = shlex.split(
                to_bytes(nspawn_args, errors='surrogate_or_strict')
            )
        else:
            nspawn_args = shlex.split(
                to_text(nspawn_args, errors='surrogate_or_strict')
            )

        local_cmd = [self.nspawn_cmd, '-D', self.ostree] + nspawn_args + [
            '--', executable, '-c', cmd]

        display.vvv("EXEC %s" % (local_cmd), host=self.ostree)
        local_cmd = [to_bytes(i, errors='surrogate_or_strict')
                     for i in local_cmd]
        p = subprocess.Popen(local_cmd, shell=False, stdin=stdin,
                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)

        return p

    def exec_command(self, cmd, in_data=None, sudoable=False):
        ''' run a command in the container '''
        super(Connection, self).exec_command(cmd, in_data=in_data,
                                             sudoable=sudoable)

        p = self._buffered_exec_command(cmd)
        stdout, stderr = p.communicate(in_data)
        return (p.returncode, stdout, stderr)

    def _prefix_login_path(self, remote_path):
        ''' Make sure that we put files into a standard path

            If a path is relative, then we need to choose where to put it.
            ssh chooses $HOME but we aren't guaranteed that a home dir will
            exist in any given container. So for now we're choosing "/"
            instead.
            This also happens to be the former default.

            Can revisit using $HOME instead if it's a problem
        '''
        if not remote_path.startswith(os.path.sep):
            remote_path = os.path.join(os.path.sep, remote_path)
        return os.path.normpath(remote_path)

    def put_file(self, in_path, out_path):
        ''' transfer a file from local to the container '''
        super(Connection, self).put_file(in_path, out_path)
        display.vvv("PUT %s TO %s" % (in_path, out_path), host=self.ostree)

        out_path = shlex_quote(self._prefix_login_path(out_path))
        try:
            with open(to_bytes(in_path, errors='surrogate_or_strict'),
                      'rb') as in_file:
                try:
                    p = self._buffered_exec_command(
                        'dd of=%s bs=%s' % (out_path, BUFSIZE),
                        stdin=in_file
                    )
                except OSError:
                    raise AnsibleError(
                        "nspawn connection requires dd command in container"
                    )
                try:
                    stdout, stderr = p.communicate()
                except:
                    traceback.print_exc()
                    raise AnsibleError("failed to transfer file %s to %s"
                                       % (in_path, out_path))
                if p.returncode != 0:
                    raise AnsibleError(
                        "failed to transfer file %s to %s:\n%s\n%s"
                        % (in_path, out_path, stdout, stderr)
                    )
        except IOError:
            raise AnsibleError("file or module does not exist at: %s"
                               % in_path)

    def fetch_file(self, in_path, out_path):
        ''' fetch a file from the container to local '''
        super(Connection, self).fetch_file(in_path, out_path)
        display.vvv("FETCH %s TO %s" % (in_path, out_path), host=self.ostree)

        in_path = shlex_quote(self._prefix_login_path(in_path))
        try:
            p = self._buffered_exec_command('dd if=%s bs=%s'
                                            % (in_path, BUFSIZE))
        except OSError:
            raise AnsibleError(
                "nspawn connection requires dd command in the container"
            )

        with open(to_bytes(out_path, errors='surrogate_or_strict'),
                  'wb+') as out_file:
            try:
                chunk = p.stdout.read(BUFSIZE)
                while chunk:
                    out_file.write(chunk)
                    chunk = p.stdout.read(BUFSIZE)
            except:
                traceback.print_exc()
                raise AnsibleError("failed to transfer file %s to %s"
                                   % (in_path, out_path))
            stdout, stderr = p.communicate()
            if p.returncode != 0:
                raise AnsibleError("failed to transfer file %s to %s:\n%s\n%s"
                                   % (in_path, out_path, stdout, stderr))

    def close(self):
        ''' terminate the connection; nothing to do here '''
        super(Connection, self).close()
        self._connected = False
<commit_msg>Revert "Add safety checks to nspawn connection plugin"<commit_after>from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

import os
import pipes
import subprocess
import traceback
import shlex

from ansible import constants as C
from ansible.errors import AnsibleError
from ansible.plugins.connection import ConnectionBase
from ansible.module_utils.basic import is_executable
from ansible.utils.unicode import to_bytes

try:
    from __main__ import display
except ImportError:
    from ansible.utils.display import Display
    display = Display()

BUFSIZE = 65536

class Connection(ConnectionBase):
    ''' Local nspawn based connections '''

    transport = 'nspawn'
    has_pipelining = True
    become_methods = frozenset(C.BECOME_METHODS)

    def __init__(self, play_context, new_stdin, *args, **kwargs):
        super(Connection, self).__init__(play_context, new_stdin,
                *args, **kwargs)

        display.vvv("NSPAWN ARGS %s" % self._play_context.nspawn_args)

        self.chroot = self._play_context.remote_addr

        if os.geteuid() != 0:
            raise AnsibleError("nspawn connection requires running as root")

        # we're running as root on the local system so do some
        # trivial checks for ensuring 'host' is actually a chroot'able dir
        if not os.path.isdir(self.chroot):
            raise AnsibleError("%s is not a directory" % self.chroot)

        chrootsh = os.path.join(self.chroot, 'bin/sh')
        if not is_executable(chrootsh):
            raise AnsibleError("%s does not look like a chrootable dir (/bin/sh missing)" % self.chroot)

        self.nspawn_cmd = 'systemd-nspawn'

    def _connect(self):
      pass

    def _buffered_exec_command(self, cmd, stdin=subprocess.PIPE):
        ''' run a command on the chroot.  This is only needed for
        implementing put_file() get_file() so that we don't have to
        read the whole file into memory.

        compared to exec_command() it looses some niceties like being
        able to return the process's exit code immediately.
        '''
        executable = (
                C.DEFAULT_EXECUTABLE.split()[0]
                if C.DEFAULT_EXECUTABLE
                else '/bin/sh')

        nspawn_args = shlex.split(self._play_context.nspawn_args)
        local_cmd = [self.nspawn_cmd, '-D', self.chroot ] + nspawn_args + [
                '--', executable, '-c', cmd]

        display.vvv("EXEC %s" % (local_cmd), host=self.chroot)
        local_cmd = map(to_bytes, local_cmd)
        p = subprocess.Popen(local_cmd, shell=False, stdin=stdin,
                stdout=subprocess.PIPE, stderr=subprocess.PIPE)

        return p

    def exec_command(self, cmd, in_data=None, sudoable=False):
        ''' run a command on the chroot '''
        super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable)

        p = self._buffered_exec_command(cmd)
        stdout, stderr = p.communicate(in_data)
        return (p.returncode, stdout, stderr)

    def _prefix_login_path(self, remote_path):
        ''' Make sure that we put files into a standard path

            If a path is relative, then we need to choose where to put it.
            ssh chooses $HOME but we aren't guaranteed that a home dir will
            exist in any given chroot.  So for now we're choosing "/" instead.
            This also happens to be the former default.

            Can revisit using $HOME instead if it's a problem
        '''
        if not remote_path.startswith(os.path.sep):
            remote_path = os.path.join(os.path.sep, remote_path)
        return os.path.normpath(remote_path)

    def put_file(self, in_path, out_path):
        ''' transfer a file from local to chroot '''
        super(Connection, self).put_file(in_path, out_path)
        display.vvv("PUT %s TO %s" % (in_path, out_path), host=self.chroot)

        out_path = pipes.quote(self._prefix_login_path(out_path))
        try:
            with open(in_path, 'rb') as in_file:
                try:
                    p = self._buffered_exec_command('dd of=%s bs=%s' % (out_path, BUFSIZE), stdin=in_file)
                except OSError:
                    raise AnsibleError("chroot connection requires dd command in the chroot")
                try:
                    stdout, stderr = p.communicate()
                except:
                    traceback.print_exc()
                    raise AnsibleError("failed to transfer file %s to %s" % (in_path, out_path))
                if p.returncode != 0:
                    raise AnsibleError("failed to transfer file %s to %s:\n%s\n%s" % (in_path, out_path, stdout, stderr))
        except IOError:
            raise AnsibleError("file or module does not exist at: %s" % in_path)

    def fetch_file(self, in_path, out_path):
        ''' fetch a file from chroot to local '''
        super(Connection, self).fetch_file(in_path, out_path)
        display.vvv("FETCH %s TO %s" % (in_path, out_path), host=self.chroot)

        in_path = pipes.quote(self._prefix_login_path(in_path))
        try:
            p = self._buffered_exec_command('dd if=%s bs=%s' % (in_path, BUFSIZE))
        except OSError:
            raise AnsibleError("chroot connection requires dd command in the chroot")

        with open(out_path, 'wb+') as out_file:
            try:
                chunk = p.stdout.read(BUFSIZE)
                while chunk:
                    out_file.write(chunk)
                    chunk = p.stdout.read(BUFSIZE)
            except:
                traceback.print_exc()
                raise AnsibleError("failed to transfer file %s to %s" % (in_path, out_path))
            stdout, stderr = p.communicate()
            if p.returncode != 0:
                raise AnsibleError("failed to transfer file %s to %s:\n%s\n%s" % (in_path, out_path, stdout, stderr))

    def close(self):
        ''' terminate the connection; nothing to do here '''
        super(Connection, self).close()
        self._connected = False
<|endoftext|>


<commit_before>from tools import field_info as field

from Tkinter import *
import threading

master = Tk()

# create gridworld out of field data

# create functions to draw field + decisions made / q values ranging from green to red
# draw field + update field

square_size = 200 # relative to field
field_x = field.x_field_length + 200
field_y = field.y_field_length + 200

rows = field_x / square_size
columns = field_y / square_size

square_display_size = 10

board_x = rows * square_display_size
board_y = columns * square_display_size

board = Canvas(master, width= board_x, height=board_y)

def render_grid():
    global square_display_size, rows, columns
    for i in range(rows):
        for j in range(columns):
            if j*square_size < 800 or j*square_size >= 6800 or i*square_size < 800 or i*square_size >= 9800:
                board.create_rectangle(i * square_display_size, j * square_display_size, (i + 1) * square_display_size,
                                       (j + 1) * square_display_size, fill="orange", width=1)
            else:
                board.create_rectangle(i*square_display_size, j*square_display_size, (i+1)*square_display_size,
                    (j+1)*square_display_size, fill="white", width=1)

    # add own and opponent goal

# add color updater

render_grid()

board.grid(row=0, column=0)

master.mainloop()

<commit_msg>added arrow & agent display, own & opp goal display<commit_after>from tools import field_info as field

from Tkinter import *
import threading
import time

master = Tk()

# create gridworld out of field data

# create functions to draw field + decisions made / q values ranging from green to red
# draw field + update field

square_size = 200 # relative to field
field_x = field.x_field_length + 200
field_y = field.y_field_length + 200

rows = field_x / square_size
columns = field_y / square_size

square_display_size = 10

board_x = rows * square_display_size
board_y = columns * square_display_size

actions = ["up","down","right","left"]

arrows = {}

agent_position = (5,5)

board = Canvas(master, width= board_x, height=board_y)

def render_grid():
    global square_display_size, rows, columns
    for i in range(rows):
        for j in range(columns):

            # own and opp goal as green and red fields
            if (3000 <= j*square_size < 4600) and (0 <= i*square_size < 800):
                board.create_rectangle(i * square_display_size, j * square_display_size, (i + 1) * square_display_size,
                                       (j + 1) * square_display_size, fill="red", width=1)
            elif (3000 <= j*square_size < 4600) and (9800 <= i*square_size < 10600):
                board.create_rectangle(i * square_display_size, j * square_display_size, (i + 1) * square_display_size,
                                       (j + 1) * square_display_size, fill="green", width=1)
            # outer field in orange
            elif j*square_size < 800 or j*square_size >= 6800 or i*square_size < 800 or i*square_size >= 9800:
                board.create_rectangle(i * square_display_size, j * square_display_size, (i + 1) * square_display_size,
                                       (j + 1) * square_display_size, fill="orange", width=1)
            # innerfield white
            else:
                board.create_rectangle(i*square_display_size, j*square_display_size, (i+1)*square_display_size,
                    (j+1)*square_display_size, fill="white", width=1)

def draw_arrow(i,j,action):
    if action == "up":
        board.create_line(i*square_display_size + 0.5*square_display_size, (j+1)*square_display_size, i*square_display_size + 0.5*square_display_size, j*square_display_size, fill="black",  arrow="last")
    elif action == "down":
        board.create_line(i*square_display_size + 0.5*square_display_size, j*square_display_size, i*square_display_size + 0.5*square_display_size, (j+1)*square_display_size, fill="black",  arrow="last")
    elif action == "right":
        board.create_line(i*square_display_size, j*square_display_size + 0.5*square_display_size, (i+1)*square_display_size, j*square_display_size + 0.5*square_display_size, fill="black",  arrow="last")
    elif action == "left":
        board.create_line((i+1)*square_display_size, j*square_display_size + 0.5*square_display_size, i*square_display_size, j*square_display_size + 0.5*square_display_size, fill="black",  arrow="last")
    else:
        print "no arrow drawn for field: ", (i,j)

def create_arrows():
    global arrows
    for i in range(rows):
        for j in range(columns):
            if (800 <= j * square_size < 6800) and (800 <= i * square_size < 9800):
                arrows[(i,j)] = board.create_line(i * square_display_size, j * square_display_size + 0.5 * square_display_size,
                                  (i + 1) * square_display_size, j * square_display_size + 0.5 * square_display_size,
                                  fill="black", arrow="last")

def update_arrow(coords, action):
    global arrows
    i = coords[0]
    j = coords[1]
    if action == "up":
        board.coords(arrows[coords], i*square_display_size + 0.5*square_display_size, (j+1)*square_display_size,
                          i*square_display_size + 0.5*square_display_size, j*square_display_size)
    elif action == "down":
        board.coords(arrows[coords], i*square_display_size + 0.5*square_display_size, j*square_display_size,
                          i*square_display_size + 0.5*square_display_size, (j+1)*square_display_size)
    elif action == "right":
        board.coords(arrows[coords], i*square_display_size, j*square_display_size + 0.5*square_display_size,
                          (i+1)*square_display_size, j*square_display_size + 0.5*square_display_size)
    elif action == "left":
        board.coords(arrows[coords], (i+1)*square_display_size, j*square_display_size + 0.5*square_display_size,
                          i*square_display_size, j*square_display_size + 0.5*square_display_size)
    else:
        print "no arrow drawn for field: ", (i,j)

# add color updater

render_grid()

board.grid(row=0, column=0)

create_arrows()
agent_display = board.create_oval(agent_position[0]*square_display_size,agent_position[1]*square_display_size,
                            (agent_position[0]+1)*square_display_size,(agent_position[1]+1)*square_display_size,fill="orange", width=1, tag="agent")

def move_agent(absolute = None, relative = None):
    global agent_position
    # set new coords for the agent
    if absolute != None:
        agent_position = absolute
    if relative != None:
        agent_position = (agent_position[0] + relative[0], agent_position[1] + relative[1])
    # display agent at new place
    board.coords(agent_display, agent_position[0] * square_display_size, agent_position[1] * square_display_size,
                 (agent_position[0] + 1) * square_display_size, (agent_position[1] + 1) * square_display_size)

def run():
    global agent_position
    while True:
        if agent_position[0] < 50:
            move_agent(relative = (1,0))
            update_arrow((agent_position),"up")
            time.sleep(0.1)
        else:
            move_agent(absolute = (5,5))

t = threading.Thread(target=run)
t.daemon = True
t.start()
master.mainloop()

<|endoftext|>


<commit_before>"""plistlib.py -- a tool to generate and parse MacOSX .plist files.

The PropertList (.plist) file format is a simple XML pickle supporting
basic object types, like dictionaries, lists, numbers and strings.
Usually the top level object is a dictionary.

To write out a plist file, use the writePlist(rootObject, pathOrFile)
function. 'rootObject' is the top level object, 'pathOrFile' is a
filename or a (writable) file object.

To parse a plist from a file, use the readPlist(pathOrFile) function,
with a file name or a (readable) file object as the only argument. It
returns the top level object (again, usually a dictionary).

To work with plist data in strings, you can use readPlistFromString()
and writePlistToString().

Values can be strings, integers, floats, booleans, tuples, lists,
dictionaries, Data or datetime.datetime objects. String values (including
dictionary keys) may be unicode strings -- they will be written out as
UTF-8.

The <data> plist type is supported through the Data class. This is a
thin wrapper around a Python string.

Generate Plist example:

    pl = dict(
        aString="Doodah",
        aList=["A", "B", 12, 32.1, [1, 2, 3]],
        aFloat = 0.1,
        anInt = 728,
        aDict=dict(
            anotherString="<hello & hi there!>",
            aUnicodeValue=u'M\xe4ssig, Ma\xdf',
            aTrueValue=True,
            aFalseValue=False,
        ),
        someData = Data("<binary gunk>"),
        someMoreData = Data("<lots of binary gunk>" * 10),
        aDate = datetime.fromtimestamp(time.mktime(time.gmtime())),
    )
    # unicode keys are possible, but a little awkward to use:
    pl[u'\xc5benraa'] = "That was a unicode key."
    writePlist(pl, fileName)

Parse Plist example:

    pl = readPlist(pathOrFile)
    print pl["aKey"]
"""

__all__ = [
    "readPlist", "writePlist", "readPlistFromString", "writePlistToString",
    "readPlistFromResource", "writePlistToResource",
    "Plist", "Data", "Dict"
]
# Note: the Plist and Dict classes have been deprecated.

import binascii
from cStringIO import StringIO
import re
try:
    from datetime import datetime
except ImportError:
    # We're running on Python < 2.3, we don't support dates here,
    # yet we provide a stub class so type dispatching works.
    class datetime(object):
        def __init__(self, *args, **kwargs):
            raise ValueError("datetime is not supported")

def readPlist(pathOrFile):
    """Read a .plist file. 'pathOrFile' may either be a file name or a
    (readable) file object. Return the unpacked root object (which
    usually is a dictionary).
    """
    didOpen = 0
    if isinstance(pathOrFile, (str, unicode)):
        pathOrFile = open(pathOrFile)
        didOpen = 1
    p = PlistParser()
    rootObject = p.parse(pathOrFile)
    if didOpen:
        pathOrFile.close()
    return rootObject

def writePlist(rootObject, pathOrFile):
    """Write 'rootObject' to a .plist file. 'pathOrFile' may either be a
    file name or a (writable) file object.
    """
    didOpen = 0
    if isinstance(pathOrFile, (str, unicode)):
        pathOrFile = open(pathOrFile, "w")
        didOpen = 1
    writer = PlistWriter(pathOrFile)
    writer.writeln("<plist version=\"1.0\">")
    writer.writeValue(rootObject)
    writer.writeln("</plist>")
    if didOpen:
        pathOrFile.close()

def readPlistFromString(data):
    """Read a plist data from a string. Return the root object.
    """
    return readPlist(StringIO(data))

def writePlistToString(rootObject):
    """Return 'rootObject' as a plist-formatted string.
    """
    f = StringIO()
    writePlist(rootObject, f)
    return f.getvalue()

def readPlistFromResource(path, restype='plst', resid=0):
    """Read plst resource from the resource fork of path.
    """
    from Carbon.File import FSRef, FSGetResourceForkName
    from Carbon.Files import fsRdPerm
    from Carbon import Res
    fsRef = FSRef(path)
    resNum = Res.FSOpenResourceFile(fsRef, FSGetResourceForkName(), fsRdPerm)
    Res.UseResFile(resNum)
    plistData = Res.Get1Resource(restype, resid).data
    Res.CloseResFile(resNum)
    return readPlistFromString(plistData)

def writePlistToResource(rootObject, path, restype='plst', resid=0):
    """Write 'rootObject' as a plst resource to the resource fork of path.
    """
    from Carbon.File import FSRef, FSGetResourceForkName
    from Carbon.Files import fsRdWrPerm
    from Carbon import Res
    plistData = writePlistToString(rootObject)
    fsRef = FSRef(path)
    resNum = Res.FSOpenResourceFile(fsRef, FSGetResourceForkName(), fsRdWrPerm)
    Res.UseResFile(resNum)
    try:
        Res.Get1Resource(restype, resid).RemoveResource()
    except Res.Error:
        pass
    res = Res.Resource(plistData)
    res.AddResource(restype, resid, '')
    res.WriteResource()
    Res.CloseResFile(resNum)

class DumbXMLWriter:

    def __init__(self, file, indentLevel=0, indent="\t"):
        self.file = file
        self.stack = []
        self.indentLevel = indentLevel
        self.indent = indent

    def beginElement(self, element):
        self.stack.append(element)
        self.writeln("<%s>" % element)
        self.indentLevel += 1

    def endElement(self, element):
        assert self.indentLevel > 0
        assert self.stack.pop() == element
        self.indentLevel -= 1
        self.writeln("</%s>" % element)

    def simpleElement(self, element, value=None):
        if value is not None:
            value = _escapeAndEncode(value)
            self.writeln("<%s>%s</%s>" % (element, value, element))
        else:
            self.writeln("<%s/>" % element)

    def writeln(self, line):
        if line:
            self.file.write(self.indentLevel * self.indent + line + "\n")
        else:
            self.file.write("\n")

# Contents should conform to a subset of ISO 8601
# (in particular, YYYY '-' MM '-' DD 'T' HH ':' MM ':' SS 'Z'.  Smaller units may be omitted with
#  a loss of precision)
_dateParser = re.compile(r"(?P<year>\d\d\d\d)(?:-(?P<month>\d\d)(?:-(?P<day>\d\d)(?:T(?P<hour>\d\d)(?::(?P<minute>\d\d)(?::(?P<second>\d\d))?)?)?)?)?Z")

def _dateFromString(s):
    order = ('year', 'month', 'day', 'hour', 'minute', 'second')
    gd = _dateParser.match(s).groupdict()
    lst = []
    for key in order:
        val = gd[key]
        if val is None:
            break
        lst.append(int(val))
    return datetime(*lst)

def _dateToString(d):
    return '%04d-%02d-%02dT%02d:%02d:%02dZ' % (
        d.year, d.month, d.day,
        d.hour, d.minute, d.second
    )

# Regex to find any control chars, except for \t \n and \r
_controlCharPat = re.compile(
    r"[\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0b\x0c\x0e\x0f"
    r"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f]")

def _escapeAndEncode(text):
    m = _controlCharPat.search(text)
    if m is not None:
        raise ValueError("strings can't contains control characters; "
                         "use plistlib.Data instead")
    text = text.replace("\r\n", "\n")       # convert DOS line endings
    text = text.replace("\r", "\n")         # convert Mac line endings
    text = text.replace("&", "&")       # escape '&'
    text = text.replace("<", "<")        # escape '<'
    text = text.replace(">", ">")        # escape '>'
    return text.encode("utf-8")             # encode as UTF-8

PLISTHEADER = """\
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
"""

class PlistWriter(DumbXMLWriter):

    def __init__(self, file, indentLevel=0, indent="\t", writeHeader=1):
        if writeHeader:
            file.write(PLISTHEADER)
        DumbXMLWriter.__init__(self, file, indentLevel, indent)

    def writeValue(self, value):
        if isinstance(value, (str, unicode)):
            self.simpleElement("string", value)
        elif isinstance(value, bool):
            # must switch for bool before int, as bool is a
            # subclass of int...
            if value:
                self.simpleElement("true")
            else:
                self.simpleElement("false")
        elif isinstance(value, int):
            self.simpleElement("integer", str(value))
        elif isinstance(value, float):
            self.simpleElement("real", repr(value))
        elif isinstance(value, dict):
            self.writeDict(value)
        elif isinstance(value, Data):
            self.writeData(value)
        elif isinstance(value, datetime):
            self.simpleElement("date", _dateToString(value))
        elif isinstance(value, (tuple, list)):
            self.writeArray(value)
        else:
            raise TypeError("unsuported type: %s" % type(value))

    def writeData(self, data):
        self.beginElement("data")
        self.indentLevel -= 1
        maxlinelength = 76 - len(self.indent.replace("\t", " " * 8) *
                                 self.indentLevel)
        for line in data.asBase64(maxlinelength).split("\n"):
            if line:
                self.writeln(line)
        self.indentLevel += 1
        self.endElement("data")

    def writeDict(self, d):
        self.beginElement("dict")
        items = d.items()
        items.sort()
        for key, value in items:
            if not isinstance(key, (str, unicode)):
                raise TypeError("keys must be strings")
            self.simpleElement("key", key)
            self.writeValue(value)
        self.endElement("dict")

    def writeArray(self, array):
        self.beginElement("array")
        for value in array:
            self.writeValue(value)
        self.endElement("array")

class _InternalDict(dict):

    # This class is needed while Dict is scheduled for deprecation:
    # we only need to warn when a *user* instantiates Dict or when
    # the "attribute notation for dict keys" is used.

    def __getattr__(self, attr):
        try:
            value = self[attr]
        except KeyError:
            raise AttributeError, attr
        from warnings import warn
        warn("Attribute access from plist dicts is deprecated, use d[key] "
             "notation instead", PendingDeprecationWarning)
        return value

    def __setattr__(self, attr, value):
        from warnings import warn
        warn("Attribute access from plist dicts is deprecated, use d[key] "
             "notation instead", PendingDeprecationWarning)
        self[attr] = value

    def __delattr__(self, attr):
        try:
            del self[attr]
        except KeyError:
            raise AttributeError, attr
        from warnings import warn
        warn("Attribute access from plist dicts is deprecated, use d[key] "
             "notation instead", PendingDeprecationWarning)

class Dict(_InternalDict):

    def __init__(self, **kwargs):
        from warnings import warn
        warn("The plistlib.Dict class is deprecated, use builtin dict instead",
             PendingDeprecationWarning)
        super(Dict, self).__init__(**kwargs)

class Plist(_InternalDict):

    """This class has been deprecated. Use readPlist() and writePlist()
    functions instead, together with regular dict objects.
    """

    def __init__(self, **kwargs):
        from warnings import warn
        warn("The Plist class is deprecated, use the readPlist() and "
             "writePlist() functions instead", PendingDeprecationWarning)
        super(Plist, self).__init__(**kwargs)

    def fromFile(cls, pathOrFile):
        """Deprecated. Use the readPlist() function instead."""
        rootObject = readPlist(pathOrFile)
        plist = cls()
        plist.update(rootObject)
        return plist
    fromFile = classmethod(fromFile)

    def write(self, pathOrFile):
        """Deprecated. Use the writePlist() function instead."""
        writePlist(self, pathOrFile)

def _encodeBase64(s, maxlinelength=76):
    # copied from base64.encodestring(), with added maxlinelength argument
    maxbinsize = (maxlinelength//4)*3
    pieces = []
    for i in range(0, len(s), maxbinsize):
        chunk = s[i : i + maxbinsize]
        pieces.append(binascii.b2a_base64(chunk))
    return "".join(pieces)

class Data:

    """Wrapper for binary data."""

    def __init__(self, data):
        self.data = data

    def fromBase64(cls, data):
        # base64.decodestring just calls binascii.a2b_base64;
        # it seems overkill to use both base64 and binascii.
        return cls(binascii.a2b_base64(data))
    fromBase64 = classmethod(fromBase64)

    def asBase64(self, maxlinelength=76):
        return _encodeBase64(self.data, maxlinelength)

    def __cmp__(self, other):
        if isinstance(other, self.__class__):
            return cmp(self.data, other.data)
        elif isinstance(other, str):
            return cmp(self.data, other)
        else:
            return cmp(id(self), id(other))

    def __repr__(self):
        return "%s(%s)" % (self.__class__.__name__, repr(self.data))

class PlistParser:

    def __init__(self):
        self.stack = []
        self.currentKey = None
        self.root = None

    def parse(self, fileobj):
        from xml.parsers.expat import ParserCreate
        parser = ParserCreate()
        parser.StartElementHandler = self.handleBeginElement
        parser.EndElementHandler = self.handleEndElement
        parser.CharacterDataHandler = self.handleData
        parser.ParseFile(fileobj)
        return self.root

    def handleBeginElement(self, element, attrs):
        self.data = []
        handler = getattr(self, "begin_" + element, None)
        if handler is not None:
            handler(attrs)

    def handleEndElement(self, element):
        handler = getattr(self, "end_" + element, None)
        if handler is not None:
            handler()

    def handleData(self, data):
        self.data.append(data)

    def addObject(self, value):
        if self.currentKey is not None:
            self.stack[-1][self.currentKey] = value
            self.currentKey = None
        elif not self.stack:
            # this is the root object
            self.root = value
        else:
            self.stack[-1].append(value)

    def getData(self):
        data = "".join(self.data)
        try:
            data = data.encode("ascii")
        except UnicodeError:
            pass
        self.data = []
        return data

    # element handlers

    def begin_dict(self, attrs):
        d = _InternalDict()
        self.addObject(d)
        self.stack.append(d)
    def end_dict(self):
        self.stack.pop()

    def end_key(self):
        self.currentKey = self.getData()

    def begin_array(self, attrs):
        a = []
        self.addObject(a)
        self.stack.append(a)
    def end_array(self):
        self.stack.pop()

    def end_true(self):
        self.addObject(True)
    def end_false(self):
        self.addObject(False)
    def end_integer(self):
        self.addObject(int(self.getData()))
    def end_real(self):
        self.addObject(float(self.getData()))
    def end_string(self):
        self.addObject(self.getData())
    def end_data(self):
        self.addObject(Data.fromBase64(self.getData()))
    def end_date(self):
        self.addObject(_dateFromString(self.getData()))

# cruft to support booleans in Python <= 2.3
import sys
if sys.version_info[:2] < (2, 3):
    # Python 2.2 and earlier: no booleans
    # Python 2.2.x: booleans are ints
    class bool(int):
        """Imitation of the Python 2.3 bool object."""
        def __new__(cls, value):
            return int.__new__(cls, not not value)
        def __repr__(self):
            if self:
                return "True"
            else:
                return "False"
    True = bool(1)
    False = bool(0)
<commit_msg>This script is part of the Python stdlib. It has nothing to do with this repository, and is therefore removed.<commit_after><|endoftext|>


<commit_before>#!/usr/bin/env python

"""
Usage:
  {0:s} -h | --help
  {0:s} <dump-file> [<decoded-dump-file>]

Options:
  -h, --help  - show help.
"""

import docopt
import os.path
import xml.dom.minidom
import base64
import sys

def parse_options():
	script_name = os.path.basename(__file__)
	return docopt.docopt(__doc__.format(script_name))

def process_options(options):
	if options['<decoded-dump-file>'] == None:
		decoded_dump_file = os.path.basename(options['<dump-file>'])
		options['<decoded-dump-file>'] = decoded_dump_file

def parse_parameters():
	options = parse_options()
	process_options(options)

	return options

def read_xml(filename):
	return xml.dom.minidom.parse(filename)

def decode_node(node):
	data = base64.b64decode(node.data)
	data = data.decode('string_escape')
	data = data.strip()
	if node.parentNode.tagName == 'text':
		data = '\n%s\n\t\t' % data

	node.data = data

def process_node(node):
	for child in node.childNodes:
		process_node(child)

	if node.nodeType == node.TEXT_NODE:
		decode_node(node)

def write_xml_to_file(dom, filename):
	with open(filename, 'w') as target_file:
		dom.writexml(target_file, encoding = 'utf-8')

def write_xml_to_stdout(dom):
	dom.writexml(sys.stdout, encoding = 'utf-8')

def write_xml(dom, target):
	if target != "-":
		write_xml_to_file(dom, target)
	else:
		write_xml_to_stdout(dom)

parameters = parse_parameters()
dom = read_xml(parameters['<dump-file>'])
process_node(dom.documentElement)
write_xml(dom, parameters['<decoded-dump-file>'])
<commit_msg>Issue #63: add custom XML outputting.<commit_after>#!/usr/bin/env python

"""
Usage:
  {0:s} -h | --help
  {0:s} <dump-file> [<decoded-dump-file>]

Options:
  -h, --help  - show help.
"""

import docopt
import os.path
import xml.dom.minidom
import base64
import sys

def parse_options():
	script_name = os.path.basename(__file__)
	return docopt.docopt(__doc__.format(script_name))

def process_options(options):
	if options['<decoded-dump-file>'] == None:
		decoded_dump_file = os.path.basename(options['<dump-file>'])
		options['<decoded-dump-file>'] = decoded_dump_file

def parse_parameters():
	options = parse_options()
	process_options(options)

	return options

def read_xml(filename):
	return xml.dom.minidom.parse(filename)

def decode_node(node):
	data = base64.b64decode(node.data)
	data = data.decode('string_escape')
	node.data = data.strip()

def process_node(node):
	for child in node.childNodes:
		process_node(child)

	if node.nodeType == node.TEXT_NODE:
		decode_node(node)

def attributes_to_string(node):
	attributes = ''
	for i in range(0, node.attributes.length):
		attribute = node.attributes.item(i)
		attributes += ' {:s}="{:s}"'.format(attribute.name, attribute.value)

	return attributes

def generate_start_tag(node, prefix):
	attributes = attributes_to_string(node)
	return prefix + '<{:s}{:s}>\n'.format(node.tagName, attributes)

def generate_end_tag(node, prefix):
	return prefix + '</{:s}>\n'.format(node.tagName)

def escape(text, prefix, text_prefix):
	text = text.replace(']]>', ']]]><![CDATA[]>')
	return '<![CDATA[\n{2:s}{0:s}\n{1:s}]]>'.format(text, prefix, text_prefix)

def text_node_to_string(node, prefix):
	if not node.data:
		return ''

	text_prefix = ''
	if node.parentNode.tagName != 'text':
		text_prefix = prefix + '\t'

	return prefix + escape(node.data, prefix, text_prefix) + '\n'

def node_to_string(node, prefix = ''):
	result = ''
	if not prefix:
		result += '<?xml version="1.1" encoding="utf-8" ?>\n'

	if node.nodeType != node.TEXT_NODE:
		result += generate_start_tag(node, prefix)
		for child in node.childNodes:
			result += node_to_string(child, prefix + '\t')
		result += generate_end_tag(node, prefix)
	else:
		result += text_node_to_string(node, prefix)

	return result

def write_xml_to_file(content, filename):
	with open(filename, 'w') as target_file:
		target_file.write(content)

def write_xml_to_stdout(content):
	print(content)

def write_xml(content, target):
	if target != "-":
		write_xml_to_file(content, target)
	else:
		write_xml_to_stdout(content)

parameters = parse_parameters()
dom = read_xml(parameters['<dump-file>'])
process_node(dom.documentElement)
content = node_to_string(dom.documentElement)
write_xml(content, parameters['<decoded-dump-file>'])
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""
from scipy import signal
from scipy import io
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import axes3d
from matplotlib import cm

#MData = scipy.io.loadmat('Mn2Au-MA70-20mW-10mW-RT-10kAVG')
#Data = MData['Daten']

def fitfunction(t,taupulse,taudecay,linearconst,A,C,t_zero):
    return  A*(-np.exp(taupulse**2/(8*taudecay**2))*(np.exp(-t/taudecay))+linearconst*t + C)*(1+scipy.special.erf(((2**0.5)*(t+t_zero-(taupulse**2/(4*taudecay))))/taupulse))

def import_redred(Filename):
    MData = io.loadmat(Filename)
    Data = MData['Daten']
    d=Data[0]
    shift=np.average(d[7460:7500:1])
    trace=30*(-Data[0]+shift)/57
    #trace=-trace  #/trace.min(axis=0)
    Time = -Data[2]
     #Data[2,np.argmin(-Data[0])]
    b, a = signal.butter(2, 0.1, 'low', analog= False)
    filtered_trace=signal.lfilter(b,a,trace)
    return(Time,filtered_trace)

def fitredred(trace1):
    trace=trace1[0]
    Time=trace1[1]
    guess=(0.16,1.68,0.0011,0.4,-0.27,0.2)
    plt.plot(Time,trace)
    popt, pcov = scipy.optimize.curve_fit(fitfunction,Time,trace,p0=guess)
    #matplotlib.pyplot.plot(Time,fitfunction(Time, *popt))
    #matplotlib.pyplot.plot(trace[1],fitfunction(trace[1], 0.16,1.63,0.0011,0.4,-0.27,0.2))

    #matplotlib.pyplot.plot(Time,trace - fitfunction(Time,  *popt))
    return(popt)
    #matplotlib.pyplot.plot(np.fft.fft(trace-fitfunction(-Data[2], *popt)))
    #matplotlib.pyplot.plot(Time,fitfunction1(Time, *popt))
    #matplotlib.pyplot.plot(Time,fitfunction2(Time, *popt))
    #matplotlib.pyplot.plot(Time,fitfunction1(Time, *popt)*fitfunction2(Time, *popt))

def fftredred(trace, Time):
    freq=scipy.fftpack.fftfreq(trace.size,np.abs((Time[0]-Time[:1])/Time.size))
    FFT = abs(scipy.fft(trace))
    plt.plot(freq, FFT)

Names=[]
angle=np.arange(0,370,10)
A=[]
Trace=[]
Time=[]
#Names.append('Mn2Au-MA125-20mW-10mW-RT-5kAV-MOKE-0degree')
#angle.append(0)
i=0
while i<37 :
    Names.append('E:\\2017-02-24\\Mn2Au-MA125-30mWhor-20mWvert-RT-1kAV-MOKE-samplerot-'+str(0+i*10)+'degree')
    i+=1
PS=[]
MData = io.loadmat(Names[1])
Data = MData['Daten']
timeShift=Data[2,np.argmin(-Data[0])]
for item in Names:
    data=import_redred(item)
    dt=data[1]
    PS.append(np.average(dt[5640:5692:1]))
    trace=data[1]
    time=data[0]+timeShift
    Trace.append(trace[0:5777:1])
    Time.append(time[0:5777:1])
    #plt.plot(time,trace)
    #fftredred(trace, time)
    #tr=import_redred(item)
    #q=tr[0]
    #A.append(np.sum(q[5650:5700]))
    #matplotlib.pyplot.plot(angle,A)
X=np.array(Time)
Angle=[]
i=np.arange(0,5777,1)
for item in i:
    Angle.append(angle)
Y=np.transpose(np.array(Angle))
Z=np.array(Trace)
fig = plt.figure(num=1)
ax = fig.add_subplot(111, projection='3d')
# Grab some test data.
#X, Y, Z = axes3d.get_test_data(0.05)

# Plot a basic wireframe.
ax.plot_surface(X, Y, Z, rstride=1, cstride=100, cmap='viridis')
ax.set_xlabel('Time(ps)', fontsize=20, labelpad=20)
ax.tick_params(axis='x', labelsize=20)
ax.tick_params(axis='y', labelsize=20)
ax.tick_params(axis='z', labelsize=20)

ax.set_ylabel('Angle (degrees)', fontsize=20, labelpad=20)
ax.set_zlabel('Kerr rotation (mrad)', fontsize=20, labelpad=20)
ax.set_title(' vertical Probe, horizontal Pump', fontsize=40)
#plt.show()

fig2=plt.figure(num=2)
ax1 = fig2.add_subplot(111)
ax1.plot(angle,PS)
ax1.set_xlabel('Angle (degrees)', fontsize=40)
ax1.set_ylabel('Kerr rotation (mrad)', fontsize=40)
ax1.set_title('Angular dependence of Kerr rotation at 2 ps \n (horizontal Probe, vertical Pump)',fontsize=40)
ax1.tick_params(axis='x', labelsize=20)
ax1.tick_params(axis='y', labelsize=20)

iteract=np.arange(0,18,1)
ass=0
assum=[]
for item in iteract:
    ass=Trace[item]+Trace[item+18]
    assum.append(ass)

crossect=[]
idx=0

for item in i:
    kr=[]
    trrr=[]
    for item2 in assum:
        tr=item2
        kr.append(tr[item])
    av=np.average(kr)
    zerro=np.max(kr-av)
    krnorm=(kr-av)/zerro
    crossect.append(krnorm)
x=Time[0]
y=angle[0:18:1]
X1, Y1=np.meshgrid(x,y)
Z1=np.transpose(np.array(crossect))
fig4 = plt.figure(num=3)
ax3 = fig4.add_subplot(111)
ax4 = fig4.add_subplot(211)
ax4.plot(Time[8],Trace[8])
# Grab some test data.
#X, Y, Z = axes3d.get_test_data(0.05)

# Plot a basic wireframe.
ax3.pcolor(X1, Y1, Z1, cmap='pink')
#ax3.set_xlabel('Time(ps)', fontsize=20, labelpad=20)
#ax3.tick_params(axis='x', labelsize=20)
#ax3.tick_params(axis='y', labelsize=20)
#ax3.tick_params(axis='z', labelsize=20)

#ax3.set_ylabel('Angle (degrees)', fontsize=20, labelpad=20)
#ax3.set_zlabel('Kerr rotation (mrad)', fontsize=20, labelpad=20)
#ax3.set_title(' vertical Probe, horizontal Pump', fontsize=40)
plt.show()

        <commit_msg>Auto stash before merge of "master" and "origin/master"<commit_after># -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""
from scipy import signal
from scipy import io
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import axes3d
from matplotlib import cm
from scipy.interpolate import interp1d

#MData = scipy.io.loadmat('Mn2Au-MA70-20mW-10mW-RT-10kAVG')
#Data = MData['Daten']

def fitfunction(t,taupulse,taudecay,linearconst,A,C,t_zero):
    return  A*(-np.exp(taupulse**2/(8*taudecay**2))*(np.exp(-t/taudecay))+linearconst*t + C)*(1+scipy.special.erf(((2**0.5)*(t+t_zero-(taupulse**2/(4*taudecay))))/taupulse))

def import_redred(Filename):
    MData = io.loadmat(Filename)
    Data = MData['Daten']
    d=Data[0]
    shift=np.average(d[7460:7500:1])
    trace=30000*(-Data[0]+shift)/57
    #trace=-trace  #/trace.min(axis=0)
    Time = -Data[2]
     #Data[2,np.argmin(-Data[0])]
    b, a = signal.butter(2, 0.1, 'low', analog= False)
    filtered_trace=signal.lfilter(b,a,trace)
    return(Time,filtered_trace)

def fitredred(trace1):
    trace=trace1[0]
    Time=trace1[1]
    guess=(0.16,1.68,0.0011,0.4,-0.27,0.2)
    plt.plot(Time,trace)
    popt, pcov = scipy.optimize.curve_fit(fitfunction,Time,trace,p0=guess)
    #matplotlib.pyplot.plot(Time,fitfunction(Time, *popt))
    #matplotlib.pyplot.plot(trace[1],fitfunction(trace[1], 0.16,1.63,0.0011,0.4,-0.27,0.2))

    #matplotlib.pyplot.plot(Time,trace - fitfunction(Time,  *popt))
    return(popt)
    #matplotlib.pyplot.plot(np.fft.fft(trace-fitfunction(-Data[2], *popt)))
    #matplotlib.pyplot.plot(Time,fitfunction1(Time, *popt))
    #matplotlib.pyplot.plot(Time,fitfunction2(Time, *popt))
    #matplotlib.pyplot.plot(Time,fitfunction1(Time, *popt)*fitfunction2(Time, *popt))

def fftredred(trace, Time):
    freq=scipy.fftpack.fftfreq(trace.size,np.abs((Time[0]-Time[:1])/Time.size))
    FFT = abs(scipy.fft(trace))
    plt.plot(freq, FFT)

Names=[]
angle=np.arange(0,370,10)
A=[]
Trace=[]
Time=[]
#Names.append('Mn2Au-MA125-20mW-10mW-RT-5kAV-MOKE-0degree')
#angle.append(0)
i=0
while i<37 :
    Names.append('E:\\2017-02-24\\Mn2Au-MA125-30mWhor-20mWvert-RT-1kAV-MOKE-samplerot-'+str(0+i*10)+'degree')
    i+=1
PS=[]
MData = io.loadmat(Names[1])
Data = MData['Daten']
timeShift=Data[2,np.argmin(-Data[0])]
for item in Names:
    data=import_redred(item)
    dt=data[1]
    PS.append(np.average(dt[5640:5692:1]))
    trace=data[1]
    time=data[0]+timeShift
    Trace.append(trace)
    Time.append(time)
    #plt.plot(time,trace)
    #fftredred(trace, time)
    #tr=import_redred(item)
    #q=tr[0]
    #A.append(np.sum(q[5650:5700]))
    #matplotlib.pyplot.plot(angle,A)
X=np.array(Time)
Angle=[]
i=np.arange(0,7500,1)
for item in i:
    Angle.append(angle)
Y=np.transpose(np.array(Angle))
Z=np.array(Trace)
fig = plt.figure(num=1)
ax = fig.add_subplot(111, projection='3d')
# Grab some test data.
#X, Y, Z = axes3d.get_test_data(0.05)

# Plot a basic wireframe.
ax.plot_surface(X, Y, Z, rstride=1, cstride=100, cmap='viridis')
ax.set_xlabel('Time(ps)', fontsize=20, labelpad=20)
ax.tick_params(axis='x', labelsize=20)
ax.tick_params(axis='y', labelsize=20)
ax.tick_params(axis='z', labelsize=20)

ax.set_ylabel('Angle (degrees)', fontsize=20, labelpad=20)
ax.set_zlabel('Kerr rotation (mrad)', fontsize=20, labelpad=20)
ax.set_title(' vertical Probe, horizontal Pump', fontsize=40)
#plt.show()

fig2=plt.figure(num=2)
ax1 = fig2.add_subplot(111)
ax1.plot(angle,PS)
ax1.set_xlabel('Angle (degrees)', fontsize=40)
ax1.set_ylabel('Kerr rotation (mrad)', fontsize=40)
ax1.set_title('Angular dependence of Kerr rotation at 2 ps \n (horizontal Probe, vertical Pump)',fontsize=40)
ax1.tick_params(axis='x', labelsize=20)
ax1.tick_params(axis='y', labelsize=20)

iteract=np.arange(0,18,1)
ass=0
assum=[]
for item in iteract:
    ass=Trace[item]+Trace[item+18]
    assum.append(ass)

crossect=[]
idx=0

for item in i:
    kr=[]
    trrr=[]
    for item2 in assum:
        tr=item2
        kr.append(tr[item])
    av=np.average(kr)
    zerro=np.max(kr-av)
    krnorm=(kr-av)/zerro
    crossect.append(krnorm)
x=Time[0]
y=angle
X1, Y1=np.meshgrid(x,y)
Z1=np.array(Trace)
fig4 = plt.figure(num=3)
ax3 = fig4.add_subplot(111)

# Grab some test data.
#X, Y, Z = axes3d.get_test_data(0.05)

# Plot a basic wireframe.
Zmin=-5
Zmax=15

fint = interp1d(y, Z1.T, kind='slinear')
ynew=np.arange(0,360,1)
Z1new = fint(ynew).T
X1new, Y1new=np.meshgrid(x,ynew)

cax =ax3.pcolormesh(X1new,Y1new,Z1new,vmin=Zmin,vmax=Zmax,  cmap='viridis')
ax3.set_xlabel('Time(ps)', fontsize=40)
ax3.tick_params(labelsize=40)

cbar=fig4.colorbar(cax)
cbar.set_label('Probe polarization rotation ($\mu$rad)',size=40)
cbar.ax.tick_params(labelsize=40)
ax3.set_ylabel(r'$\alpha$ (degrees)', fontsize=40, labelpad=20)

plt.show()

        <|endoftext|>