コード例 #1
0
ファイル: controller.py プロジェクト: Gaozmmm/LASDiA
    def plotMiddle(self):
        """Function to plot the graph on the Middle Canvas"""

        self.ui.factorPlot.canvas.ax.cla()
        self.ui.factorPlot.canvas.ax.grid(True)

        self.elementList = Utility.molToElemList(self.molecule)
        self.elementParameters = Utility.read_parameters(
            self.elementList, "./elementParameters.txt")

        if self.ui.formFactorCheck.isChecked():
            # print("test fe check")
            self.Q, self.I_Q, self.Qbkg, self.Ibkg_Q = UtilityAnalysis.check_data_length(
                self.Q, self.I_Q, self.Qbkg, self.Ibkg_Q, self.ui.minQ.value(),
                self.ui.maxQ.value())
            self.fe_Q, self.Ztot = MainFunctions.calc_eeff(
                self.elementList, self.Q, self.elementParameters)

            self.ui.factorPlot.canvas.ax.plot(self.Q,
                                              self.fe_Q,
                                              label=r"$f_e(Q)$")
            self.ui.factorPlot.canvas.ax.legend()
            self.ui.factorPlot.canvas.draw()
        # else:
        #     # print("test unchecked")
        #     self.ui.factorPlot.canvas.ax.lines.pop(0)
        #     self.ui.factorPlot.canvas.draw()

        if self.ui.SQCheck.isChecked():
            S_Q = self.SQ()
            self.ui.factorPlot.canvas.ax.plot(self.Q, S_Q, label=r"$S(Q)$")
            self.ui.factorPlot.canvas.ax.legend()
            self.ui.factorPlot.canvas.draw()

        if self.ui.incohCheck.isChecked():
            self.Iincoh_Q = MainFunctions.calc_Iincoh(self.elementList, self.Q,
                                                      self.elementParameters)

            self.ui.factorPlot.canvas.ax.plot(self.Q,
                                              self.Iincoh_Q,
                                              label=r"$I_{incoh}(Q)$")
            self.ui.factorPlot.canvas.ax.legend()
            self.ui.factorPlot.canvas.draw()

        if self.ui.QiQCheck.isChecked():
            self.Sinf = MainFunctions.calc_Sinf(self.elementList, self.fe_Q,
                                                self.Q, self.Ztot,
                                                self.elementParameters)
            self.i_Q = MainFunctions.calc_iQ(S_Q, self.Sinf)
            # self.r = MainFunctions.calc_r(self.Q)
            Qi_Q = self.Q * self.i_Q

            self.ui.factorPlot.canvas.ax.plot(self.Q, Qi_Q, label=r"$Qi(Q)$")
            self.ui.factorPlot.canvas.ax.legend()
            self.ui.factorPlot.canvas.draw()
コード例 #2
0
ファイル: test_CommandLine.py プロジェクト: imweijh/plugins
    def test3_checkOrArgGroups(self):
        """
        Given no argument while expecting 2 'orArg' arguments in a single group,
        Should return 'False' and an error message
        """
        myUtility = Utility.Utility()
        myDebug = Debug.Debug()

        myCommandLine = CommandLine.CommandLine(description='Blah blah blah.',
                                                objDebug=myDebug,
                                                objUtility=myUtility)

        myCommandLine._argDict['arg1'] = {
            'value': None,
            'orArgGroup': 'group1'
        }

        myCommandLine._argDict['arg2'] = {
            'value': None,
            'orArgGroup': 'group1'
        }

        orArgsAreOk, message = myCommandLine.checkOrArgGroups()
        self.assertFalse(orArgsAreOk)
        self.assertNotEqual(message, '')
コード例 #3
0
ファイル: test_CommandLine.py プロジェクト: imweijh/plugins
    def test3_checkArgsMatchRules(self):
        """
        Given 2 invalid arguments 'integer1' and 'integer2',
        Should return 'False'
        """
        integer1Value = 12.34
        integer2Value = 'a'
        integerRule = '(\d+)'

        myUtility = Utility.Utility()
        myDebug = Debug.Debug()

        myCommandLine = CommandLine.CommandLine(description='Blah blah blah.',
                                                objDebug=myDebug,
                                                objUtility=myUtility)

        myCommandLine._argDict['integer1'] = {
            'value': integer1Value,
            'rule': integerRule,
        }
        myCommandLine._argDict['integer2'] = {
            'value': integer2Value,
            'rule': integerRule,
        }

        self.assertEqual(myCommandLine.checkArgsMatchRules(), False)
コード例 #4
0
ファイル: test_Utility.py プロジェクト: imweijh/plugins
    def test1_isNumber(self):
        """
        Given the number 42
	should return True
        """
        myUtility = Utility.Utility()
        self.assertEqual(myUtility.isNumber(42), True)
コード例 #5
0
ファイル: test_Utility.py プロジェクト: imweijh/plugins
    def test4_isNumber(self):
        """
        Given the number '' (empty string)
	should return False
        """
        myUtility = Utility.Utility()
        self.assertEqual(myUtility.isNumber(''), False)
コード例 #6
0
ファイル: controller.py プロジェクト: Gaozmmm/LASDiA
    def import_data(self):
        """Function to load and plot the data file"""

        # commented just for testing
        # if self.ui.dataFileName.toPlainText() == "":
        # path, _ = QtWidgets.QFileDialog.getOpenFileName(self, "Load Data File",
        # r"../data/cea_files/Ar", "Data File(*chi *xy)")
        # else:
        # path = self.dirpath + "/" + self.ui.dataFileName.toPlainText()
        # # if self.ui.dataPathName.toPlainText() == "":
        # # self.dirpath = str(QtWidgets.QFileDialog.getExistingDirectory(self, "Open directory",
        # # r"..\data\cea_files\Ar", QtWidgets.QFileDialog.ShowDirsOnly))
        # # else:
        # # self.dirpath = self.ui.dataPathName.toPlainText()
        # # path = self.dirpath + "/" + self.ui.dataFileName.toPlainText()

        path = r"../data/cea_files/Ar/HT2_034T++_rem.chi"
        pathDir, fileName = os.path.split(path)
        self.ui.dataPathName.setPlainText(pathDir)
        self.ui.dataFileName.setPlainText(fileName)

        self.Q, self.I_Q = Utility.read_file(path)
        self.orgQ = self.Q
        self.orgI_Q = self.I_Q

        self.ui.rawDataPlot.canvas.ax.plot(self.Q, self.I_Q, "b", label="Data")
        self.ui.rawDataPlot.canvas.ax.legend()
        self.ui.rawDataPlot.canvas.draw()
コード例 #7
0
ファイル: test_Utility.py プロジェクト: imweijh/plugins
    def test5_isNumber(self):
        """
        Given the string '1.2.3'
	should return False
        """
        myUtility = Utility.Utility()
        self.assertEqual(myUtility.isNumber('1.2.3'), False)
コード例 #8
0
ファイル: controller.py プロジェクト: Gaozmmm/LASDiA
    def import_bkg(self):
        """Function to load and plot the bkg file"""

        # commented just for testing
        # if self.ui.bkgFileName.toPlainText() == "":
        # path, _ = QtWidgets.QFileDialog.getOpenFileName(self, "Load Bkg File",
        # r"../data/cea_files/Ar", "Data File(*chi *xy)")
        # else:
        # path = self.dirpath + "/" + self.ui.bkgFileName.toPlainText()

        path = r"../data/cea_files/Ar/HT2_036T++_rem.chi"
        pathDir, fileName = os.path.split(path)
        self.ui.dataPathName.setPlainText(pathDir)
        self.ui.bkgFileName.setPlainText(fileName)

        self.Qbkg, self.Ibkg_Q = Utility.read_file(path)
        self.orgQbkg = self.Qbkg
        self.orgIbkg_Q = self.Ibkg_Q
        path = ""

        self.ui.rawDataPlot.canvas.ax.plot(self.Qbkg,
                                           self.Ibkg_Q,
                                           "g--",
                                           label="Bkg")
        self.ui.rawDataPlot.canvas.ax.legend()
        self.ui.rawDataPlot.canvas.draw()
コード例 #9
0
ファイル: test_Utility.py プロジェクト: imweijh/plugins
    def test2_isNumber(self):
        """
        Given the number -273.15
	should return True
        """
        myUtility = Utility.Utility()
        self.assertEqual(myUtility.isNumber(-273.15), True)
コード例 #10
0
ファイル: Geometry.py プロジェクト: Gaozmmm/LASDiA
def geometry_correction(Q, I_Q, Qbkg, Ibkg_Q, variables, phi_matrix_flag):
    """Function to calcultate all intensity geometrical corrections.
    
    Parameters
    ----------
    Q               : numpy array
                      momentum transfer (nm^-1)
    I_Q             : numpy array
                      measured scattering intensity
    Qbkg            : numpy array
                      background momentum transfer (nm^-1)
    Ibkg_Q          : numpy array
                      background scattering intensity
    variables       : module
                      input variables setted by the user
    phi_matrix_flag : string
                      flag for the phi matrix calculation:
                      "y": calculate phi matrix and save on file
                      "n": read the phi matrix from file
    
    Returns
    -------
    I_Q             : numpy array
                      corrected measured sample intensity
    Ibkg_Q          : numpy array
                      corrected background intensity
    """

    two_theta = UtilityAnalysis.Qto2theta(Q)

    abs_corr_factor = calcAbsCorrection(variables.abs_length, \
        two_theta, variables.dac_thickness, 0)

    num_point = 1000

    phi_matrix_path = "./phi_matrix_" + variables.molecule

    if phi_matrix_flag.lower() == "y":
        ws1, ws2, r1, r2, d = Utility.read_MCC_file(variables.MCC_path,
                                                    variables.MCC_type)
        thickness_sampling, phi_matrix = calc_phi_matrix(variables.phi_matrix_thickness, \
            two_theta, ws1, ws2, r1, r2, d, num_point)
        np.save(phi_matrix_path, phi_matrix)
    else:
        thickness_sampling = np.linspace(0,
                                         variables.phi_matrix_thickness,
                                         num=num_point)
        phi_matrix = np.load(phi_matrix_path + ".npy")

    T_MCC_sample3, T_MCC_DAC3, T_MCC_ALL3 = calc_T_MCC(0.003, thickness_sampling, \
        phi_matrix, "y")
    T_MCC_sample4, T_MCC_DAC4, T_MCC_ALL4 = calc_T_MCC(0.004, thickness_sampling, \
        phi_matrix, "y")
    T_MCC_corr_factor_bkg = calc_T_DAC_MCC_bkg_corr(T_MCC_DAC4, T_MCC_DAC3)

    I_Q = I_Q / (abs_corr_factor * T_MCC_sample4)
    Ibkg_Q = Ibkg_Q * T_MCC_corr_factor_bkg / (abs_corr_factor * T_MCC_sample4)

    return (I_Q, Ibkg_Q)
コード例 #11
0
ファイル: test_Utility.py プロジェクト: imweijh/plugins
    def test3_isNumber(self):
        """
        Given the number "this is not a number, AAARGL!"
	should return False
        """
        myUtility = Utility.Utility()
        self.assertEqual(myUtility.isNumber('this is not a number, AAARGL!'),
                         False)
コード例 #12
0
ファイル: test_Utility.py プロジェクト: imweijh/plugins
    def test1_computePercentage(self):
        """
        Given a number and a total (both are >0)
	should return a percentage (float) : 0 <= number <= 100
        """
        myUtility = Utility.Utility()
        number = 12
        total = 42
        percentage = myUtility.computePercentage(number, total)
        self.assertTrue((percentage >= 0) and (percentage <= 100))
コード例 #13
0
ファイル: test_Utility.py プロジェクト: imweijh/plugins
    def test2_computePercentage(self):
        """
        Given any number and total == 0
	should return 0
        """
        myUtility = Utility.Utility()
        number = 12
        total = 0
        expected = 0
        self.assertEqual(myUtility.computePercentage(number, total), expected)
コード例 #14
0
ファイル: test_CheckLocalCpu.py プロジェクト: imweijh/plugins
    def test3_computeExitStatus(self):
        """
        Given a CPU load > crit threshold
	should return the 'CRITICAL' Nagios plugin exit status
        """
        self._objUtility = Utility.Utility()
        self._objDebug = Debug.Debug()
        myPlugin = CheckLocalCpu.CheckLocalCpu(
            name='CHECK LOCAL CPU',
            objDebug=self._objDebug,
        )

        myPlugin.cpuUsagePercent = critical + 1

        exitStatus = myPlugin.computeExitStatus(warningThreshold=warning,
                                                criticalThreshold=critical)
        self.assertEqual(exitStatus, 'CRITICAL')
コード例 #15
0
ファイル: IgorFunctions.py プロジェクト: Gaozmmm/LASDiA
def calc_IFFT_Fr(r, F_r):
    """Function to calculate the FFT following the IGOR procedure.
    I do not agree with this procedure, but I follow it to compare my results
    with Igor Pro's ones.
    
    Parameters
    ----------
    r      : numpy array
             atomic distance (nm)
    F_r    : numpy array
             F(r)
    
    Returns
    -------
    Q      : numpy array
             momentum transfer (nm^-1)
    Qi_Q   : numpy array
             Qi(Q)
    """

    NumPoints = 2**math.ceil(math.log(len(F_r)-1)/math.log(2))
    F_r = Utility.resize_zero(F_r, NumPoints)
    Q = np.linspace(0.0, 109, 550)
    DelQ = 2*np.pi/(np.mean(np.diff(r))*NumPoints)
    meanDeltar = np.mean(np.diff(r))
    Q1 = fftpack.fftfreq(r.size, meanDeltar)
    Qi_Q = fftpack.fft(F_r)
    Qi_Q = Qi_Q[np.where(Q1>=0.0)]
    Qi_Q = -np.imag(Qi_Q)*meanDeltar
    Q1 = np.arange(0.0, 0.0+DelQ*len(Qi_Q), DelQ)
    
    idxArray = np.zeros(550, dtype=np.int)
    for i in range(len(Q)):
        idxArray[i], _ = UtilityAnalysis.find_nearest(Q1, Q[i])
    Qi_Q = Qi_Q[idxArray]
    
    return (Q, Qi_Q)
コード例 #16
0
ファイル: IgorFunctions.py プロジェクト: Gaozmmm/LASDiA
def calc_FFT_QiQ(Q, Qi_Q, QmaxIntegrate):
    """Function to calculate the FFT following the Igor Pro procedure.
    I do not agree with this procedure, but I follow it to compare my results
    with Igor Pro's ones.
    
    Parameters
    ----------
    Q             : numpy array
                    momentum transfer (nm^-1)
    Qi_Q          : numpy array
                    Q*i(Q)
    
    QmaxIntegrate : float
                    maximum Q value for the integrations
    
    Returns
    -------
    r             : numpy array
                    atomic distance (nm)
    F_r           : numpy array
                    F(r)
    """

    pMax, elem = UtilityAnalysis.find_nearest(Q, QmaxIntegrate)
    NumPoints = 2*2*2**math.ceil(math.log(5*(pMax+1))/math.log(2))
    DelR = 2*np.pi/(np.mean(np.diff(Q))*NumPoints)
    Qi_Q = Utility.resize_zero(Qi_Q[Q<=QmaxIntegrate], NumPoints)
    Qi_Q[pMax+1:] = 0.0
    Q = np.arange(np.amin(Q), np.amin(Q)+np.mean(np.diff(Q))*NumPoints, np.mean(np.diff(Q)))
    r = MainFunctions.calc_r(Q)
    F_r = fftpack.fft(Qi_Q)
    F_r = F_r[np.where(r>=0.0)]
    F_r = -np.imag(F_r)*np.mean(np.diff(Q))*2/np.pi
    r = np.arange(0.0, 0.0+DelR*len(F_r), DelR)
    
    return (r, F_r)
コード例 #17
0
def calc_iintra(Q, fe_Q, Ztot, QmaxIntegrate, maxQ, elementList, element, x, y,
                z, elementParameters):
    """Function to calculate the intramolecular contribution of i(Q) (eq. 41).

    Parameters
    ----------
    Q                 : numpy array
                        momentum transfer (nm^-1)
    fe_Q              : numpy array
                        effective electric form factor
    Ztot              : int
                        total Z number
    QmaxIntegrate     : float
                        maximum Q value for the intagrations
    maxQ              : float
                        maximum Q value
    elementList       : dictionary("element": multiplicity)
                        chemical elements of the sample with their multiplicity
                        element      : string
                                       chemical element
                        multiplicity : int
                                       chemical element multiplicity
    element           : string array
                        array with the elements in the xyz_file
    x, y, z           : float array
                        atomic coordinate in the xyz_file (nm)
    elementParameters : dictionary("element": parameters)
                        chemical elements of the sample with their parameters
                        element    : string
                                     chemical element
                        parameters : list
                                     list of the parameters
                                     (Z, a1, b1, a2, b2, a3, b3, a4, b4, c, M, K, L)

    Returns
    -------
    iintra_Q          : numpy array
                        intramolecular contribution of i(Q)
    """

    iintra_Q = np.zeros(Q.size)
    sinpq = np.zeros(Q.size)

    for ielem in range(len(element)):
        for jelem in range(len(element)):
            if ielem != jelem:
                Kpi = MainFunctions.calc_Kp(fe_Q, element[ielem], Q,
                                            elementParameters)
                Kpj = MainFunctions.calc_Kp(fe_Q, element[jelem], Q,
                                            elementParameters)
                KK = Kpi * Kpj
                d = Utility.calc_distMol(x[ielem], y[ielem], z[ielem],
                                         x[jelem], y[jelem], z[jelem])
                if d != 0.0:
                    iintra_Q += KK * np.sin(d * Q) / (d * Q)
                    iintra_Q[Q == 0.0] = KK

    iintra_Q[(Q > QmaxIntegrate) & (Q <= maxQ)] = 0.0
    iintra_Q /= Ztot**2
    # iintra_Q /= 3

    return iintra_Q
コード例 #18
0
#                      pip install psutil
#                   Installing "psutil" this way requires the (Debian) packages :
#                       python-pip
#                       python-dev
#
# KNOWN BUGS AND LIMITATIONS :
#               1.
#
########################################## ##########################################################

from modules import CommandLine
from modules import CheckLocalCpu
from modules import Debug
from modules import Utility

myUtility = Utility.Utility()
myDebug = Debug.Debug()

myCommandLine = CommandLine.CommandLine(
    description='Check the local CPU usage.',
    objDebug=myDebug,
    objUtility=myUtility)

myPlugin = CheckLocalCpu.CheckLocalCpu(
    name='CHECK LOCAL CPU',
    objDebug=myDebug,
)

myCommandLine.declareArgument({
    'shortOption': 'w',
    'longOption': 'warning',
コード例 #19
0
ファイル: Formalism.py プロジェクト: Gaozmmm/LASDiA
def calc_iintraFZ(Q, QmaxIntegrate, maxQ, elementList, element, x, y, z,
                  elementParameters, aff_mean_squared):
    """Function to calculate the intramolecular contribution of i(Q) (eq. 41).

    Parameters
    ----------
    Q                 : numpy array
                        momentum transfer (nm^-1)
    fe_Q              : numpy array
                        effective electric form factor
    Ztot              : int
                        total Z number
    QmaxIntegrate     : float
                        maximum Q value for the intagrations
    maxQ              : float
                        maximum Q value
    elementList       : dictionary("element": multiplicity)
                        chemical elements of the sample with their multiplicity
                        element      : string
                                       chemical element
                        multiplicity : int
                                       chemical element multiplicity
    element           : string array
                        array with the elements in the xyz_file
    x, y, z           : float array
                        atomic coordinate in the xyz_file (nm)
    elementParameters : dictionary("element": parameters)
                        chemical elements of the sample with their parameters
                        element    : string
                                     chemical element
                        parameters : list
                                     list of the parameters
                                     (Z, a1, b1, a2, b2, a3, b3, a4, b4, c, M, K, L)

    Returns
    -------
    iintra_Q          : numpy array
                        intramolecular contribution of i(Q)
    """

    iintra_Q = np.zeros(Q.size)
    sinpq = np.zeros(Q.size)

    for ielem in range(len(element)):
        for jelem in range(len(element)):
            if ielem != jelem:
                # print(ielem, jelem)
                # print(type(element[ielem]))
                # print(element[ielem], elementList[element[ielem]], element[jelem], elementList[element[jelem]])
                f_Qi = MainFunctions.calc_aff(element[ielem], Q,
                                              elementParameters)
                f_Qj = MainFunctions.calc_aff(element[jelem], Q,
                                              elementParameters)
                f_i = np.mean(elementList[element[ielem]] * f_Qi / 3)
                f_j = np.mean(elementList[element[jelem]] * f_Qj / 3)
                # f_i = np.mean(f_Qi)
                # f_j = np.mean(f_Qj)
                ff = f_i * f_j
                d = Utility.calc_distMol(x[ielem], y[ielem], z[ielem],
                                         x[jelem], y[jelem], z[jelem])
                if d != 0.0:
                    iintra_Q += ff * np.sin(d * Q) / (d * Q)
                    iintra_Q[Q == 0.0] = ff

    iintra_Q[(Q > QmaxIntegrate) & (Q <= maxQ)] = 0.0
    iintra_Q /= np.mean(aff_mean_squared)
    # iintra_Q /= 3

    return iintra_Q
コード例 #20
0
ファイル: controller.py プロジェクト: Gaozmmm/LASDiA
    def SQ(self):
        """Function to calculate and plot the structure factor S(Q)"""

        self.elementList = Utility.molToElemList(self.molecule)
        # self.elementList = Utility.molToElemList("Ar")
        self.elementParameters = Utility.read_parameters(
            self.elementList, "./elementParameters.txt")

        # print(elementList)
        # print(elementParameters)

        self.Q, self.I_Q, self.Qbkg, self.Ibkg_Q = UtilityAnalysis.check_data_length(
            self.Q, self.I_Q, self.Qbkg, self.Ibkg_Q, self.ui.minQ.value(),
            self.ui.maxQ.value())

        two_theta = UtilityAnalysis.Qto2theta(self.Q)
        absCorrFactor = Geometry.calcAbsCorrection(
            self.ui.absLength.value(), two_theta, self.ui.dacThickness.value(),
            self.ui.dacAngle.value())
        self.I_Q = self.I_Q / absCorrFactor
        self.Ibkg_Q = self.Ibkg_Q / absCorrFactor

        self.fe_Q, self.Ztot = MainFunctions.calc_eeff(self.elementList,
                                                       self.Q,
                                                       self.elementParameters)
        self.Iincoh_Q = MainFunctions.calc_Iincoh(self.elementList, self.Q,
                                                  self.elementParameters)
        self.J_Q = MainFunctions.calc_JQ(self.Iincoh_Q, self.Ztot, self.fe_Q)
        self.Sinf = MainFunctions.calc_Sinf(self.elementList, self.fe_Q,
                                            self.Q, self.Ztot,
                                            self.elementParameters)

        self.dampingFunct = UtilityAnalysis.calc_dampingFunction(
            self.Q,
            self.ui.dampingFactor.value(), self.ui.QmaxIntegrate.value(),
            self.ui.dampingFunction.currentText())

        Isample_Q = MainFunctions.calc_IsampleQ(
            self.I_Q, self.ui.scaleFactorValue.value(), self.Ibkg_Q)
        alpha = MainFunctions.calc_alpha(
            self.J_Q[self.Q <= self.ui.QmaxIntegrate.value()], self.Sinf,
            self.Q[self.Q <= self.ui.QmaxIntegrate.value()],
            Isample_Q[self.Q <= self.ui.QmaxIntegrate.value()],
            self.fe_Q[self.Q <= self.ui.QmaxIntegrate.value()], self.Ztot,
            self.ui.densityValue.value())
        Icoh_Q = MainFunctions.calc_Icoh(alpha, Isample_Q, self.Iincoh_Q)

        S_Q = MainFunctions.calc_SQ(Icoh_Q, self.Ztot, self.fe_Q, self.Sinf,
                                    self.Q, self.ui.minQ.value(),
                                    self.ui.QmaxIntegrate.value(),
                                    self.ui.maxQ.value())
        Ssmooth_Q = UtilityAnalysis.calc_SQsmoothing(
            self.Q, S_Q, self.Sinf, self.ui.smoothingFactor.value(),
            self.ui.minQ.value(), self.ui.QmaxIntegrate.value(),
            self.ui.maxQ.value())
        self.SsmoothDamp_Q = UtilityAnalysis.calc_SQdamp(
            Ssmooth_Q, self.Sinf, self.dampingFunct)

        # self.ui.factorPlot.canvas.ax.plot(self.Q, self.SsmoothDamp_Q, "b", label=r"$S(Q)$")
        # self.ui.factorPlot.canvas.ax.legend()
        # self.ui.factorPlot.canvas.draw()

        return self.SsmoothDamp_Q
コード例 #21
0
# from modules import Geometry
from modules import IgorFunctions
# from modules import KaplowMethod
from modules import MainFunctions
# from modules import Minimization
from modules import Optimization
from modules import Utility
from modules import UtilityAnalysis

# from PyQt5.QtWidgets import QApplication, QVBoxLayout, QWidget

if __name__ == "__main__":

    # ---------------------------Files reading---------------------------------

    variables = Utility.read_inputFile("./inputFile.txt")

    elementList = Utility.molToelemList(variables.molecule)
    elementParameters = Utility.read_parameters(elementList,
                                                variables.element_params_path)

    path = Utility.path_xyz_file(variables.molecule)
    numAtoms, element, x, y, z = Utility.read_xyz_file(path)

    Q, I_Q = Utility.read_file(variables.data_file)
    Qbkg, Ibkg_Q = Utility.read_file(variables.bkg_file)

    # -------------------Preliminary calculation-------------------------------

    fe_Q, Ztot = MainFunctions.calc_eeff(elementList, Q, elementParameters)
    Iincoh_Q = MainFunctions.calc_Iincoh(elementList, Q, elementParameters)
コード例 #22
0
ファイル: controller.py プロジェクト: Gaozmmm/LASDiA
    def Optimization(self):
        """Function to optimize and plot F(r)"""

        #-------------------Intra-molecular components-----------------------------

        # numAtoms, element, x, y, z = Utility.read_xyz_file(self.XYZFilePath)
        numAtoms, element, x, y, z = Utility.read_xyz_file(
            "/Users/ciccio/work/ID27/LASDiA/xyzFiles/Ar.xyz")

        iintra_Q = Optimization.calc_iintra(self.Q, self.fe_Q, self.Ztot,
                                            self.ui.QmaxIntegrate.value(),
                                            self.ui.maxQ.value(),
                                            self.elementList, element, x, y, z,
                                            self.elementParameters)
        iintradamp_Q = UtilityAnalysis.calc_iintradamp(iintra_Q,
                                                       self.dampingFunct)
        Qiintradamp_Q = self.Q * iintradamp_Q
        rintra, Fintra_r = MainFunctions.calc_Fr(
            self.Q[self.Q <= self.ui.QmaxIntegrate.value()],
            Qiintradamp_Q[self.Q <= self.ui.QmaxIntegrate.value()])

        scaleFactor = self.ui.scaleFactorValue.value()
        density0 = self.ui.densityValue.value()

        # ----------------------First scale minimization---------------------------

        scaleStep = 0.05

        # sth = 0.008
        # s0th = 0.006
        sth = 0.0
        s0th = 0.0
        phi_matrix = 0.0
        thickness_sampling = 0.0

        scaleFactor = Minimization.OptimizeScale(
            self.Q, self.I_Q, self.Ibkg_Q, self.J_Q, self.Iincoh_Q, self.fe_Q,
            self.ui.maxQ.value(), self.ui.minQ.value(),
            self.ui.QmaxIntegrate.value(), self.Ztot, density0,
            scaleFactor, self.Sinf, self.ui.smoothingFactor.value(),
            self.ui.rmin.value(), self.dampingFunct, Fintra_r,
            self.ui.iterations.value(), scaleStep, sth, s0th,
            thickness_sampling, phi_matrix, "n")

        # ----------------------First density minimization-------------------------

        densityStep = density0 / 50
        densityStepEnd = density0 / 250

        density = Minimization.OptimizeDensity(
            self.Q, self.I_Q, self.Ibkg_Q, self.J_Q, self.Iincoh_Q, self.fe_Q,
            self.ui.maxQ.value(), self.ui.minQ.value(),
            self.ui.QmaxIntegrate.value(), self.Ztot, density0,
            scaleFactor, self.Sinf, self.ui.smoothingFactor.value(),
            self.ui.rmin.value(), self.dampingFunct, Fintra_r,
            self.ui.iterations.value(), densityStep, densityStepEnd, sth, s0th,
            thickness_sampling, phi_matrix, "n")

        # print("density0, density", density0, density)
        numLoopIteration = 0

        while 1:
            if np.abs(density - density0) > density / 25:
                # print("First")
                scaleStep = 0.006
                densityStep = density / 10
                WSamplestep = 0.0008
                WRefstep = 0.0008
            elif np.abs(density - density0) > density / 75:
                # print("Second")
                scaleStep = 0.0006
                densityStep = density / 100
                WSamplestep = 0.0002
                WRefstep = 0.0002
            else:
                # print("Third")
                scaleStep = 0.00006
                densityStep = density / 1000
                WSamplestep = 0.0001
                WRefstep = 0.0001

            scaleFactor = Minimization.OptimizeScale(
                self.Q, self.I_Q, self.Ibkg_Q, self.J_Q, self.Iincoh_Q,
                self.fe_Q, self.ui.maxQ.value(), self.ui.minQ.value(),
                self.ui.QmaxIntegrate.value(), self.Ztot, density,
                scaleFactor, self.Sinf, self.ui.smoothingFactor.value(),
                self.ui.rmin.value(), self.dampingFunct, Fintra_r,
                self.ui.iterations.value(), scaleStep, sth, s0th,
                thickness_sampling, phi_matrix, "n")

            density0 = density

            density = Minimization.OptimizeDensity(
                self.Q, self.I_Q, self.Ibkg_Q, self.J_Q, self.Iincoh_Q,
                self.fe_Q, self.ui.maxQ.value(), self.ui.minQ.value(),
                self.ui.QmaxIntegrate.value(), self.Ztot, density0,
                scaleFactor, self.Sinf, self.ui.smoothingFactor.value(),
                self.ui.rmin.value(), self.dampingFunct, Fintra_r,
                self.ui.iterations.value(), densityStep, density / 250, sth,
                s0th, thickness_sampling, phi_matrix, "n")

            numLoopIteration += 1
            # print("numLoopIteration", numLoopIteration, scaleFactor, density)
            if (np.abs(density - density0) > np.abs(
                    density / 2500)) and (numLoopIteration <= 30):
                continue
            else:
                break

        # print("final scale", scaleFactor, "final density", density)

        self.ui.scaleFactorValue.setValue(scaleFactor)
        self.ui.densityValue.setValue(density)

        Isample_Q = MainFunctions.calc_IsampleQ(self.I_Q, scaleFactor,
                                                self.Ibkg_Q)
        alpha = MainFunctions.calc_alpha(
            self.J_Q[self.Q <= self.ui.QmaxIntegrate.value()], self.Sinf,
            self.Q[self.Q <= self.ui.QmaxIntegrate.value()],
            Isample_Q[self.Q <= self.ui.QmaxIntegrate.value()],
            self.fe_Q[self.Q <= self.ui.QmaxIntegrate.value()], self.Ztot,
            density)
        Icoh_Q = MainFunctions.calc_Icoh(alpha, Isample_Q, self.Iincoh_Q)

        S_Q = MainFunctions.calc_SQ(Icoh_Q, self.Ztot, self.fe_Q, self.Sinf,
                                    self.Q, self.ui.minQ.value(),
                                    self.ui.QmaxIntegrate.value(),
                                    self.ui.maxQ.value())

        Ssmooth_Q = UtilityAnalysis.calc_SQsmoothing(
            self.Q, S_Q, self.Sinf, self.ui.smoothingFactor.value(),
            self.ui.minQ.value(), self.ui.QmaxIntegrate.value(),
            self.ui.maxQ.value())

        SsmoothDamp_Q = UtilityAnalysis.calc_SQdamp(Ssmooth_Q, self.Sinf,
                                                    self.dampingFunct)

        i_Q = MainFunctions.calc_iQ(SsmoothDamp_Q, self.Sinf)

        Qi_Q = self.Q * i_Q
        r, F_r = MainFunctions.calc_Fr(
            self.Q[self.Q <= self.ui.QmaxIntegrate.value()],
            Qi_Q[self.Q <= self.ui.QmaxIntegrate.value()])
        Fopt_r, deltaFopt_r = Optimization.calc_optimize_Fr(
            self.ui.iterations.value(), F_r, Fintra_r, density,
            i_Q[self.Q <= self.ui.QmaxIntegrate.value()],
            self.Q[self.Q <= self.ui.QmaxIntegrate.value()], self.Sinf,
            self.J_Q[self.Q <= self.ui.QmaxIntegrate.value()], r,
            self.ui.rmin.value(), "n")

        Scorr_Q = MainFunctions.calc_SQCorr(Fopt_r, r, self.Q, self.Sinf)

        self.ui.distfuncPlot.canvas.ax.plot(r,
                                            Fopt_r,
                                            "g",
                                            label=r"$F_{opt}(r)$")
        self.ui.distfuncPlot.canvas.ax.legend()
        self.ui.distfuncPlot.canvas.draw()

        self.ui.factorPlot.canvas.ax.plot(self.Q,
                                          Scorr_Q,
                                          "g",
                                          label=r"$S_{opt}(Q)$")
        self.ui.factorPlot.canvas.ax.legend()
        self.ui.factorPlot.canvas.draw()
コード例 #23
0
ファイル: LASDiAScript.py プロジェクト: Gaozmmm/LASDiA
        default_dir = environ["HOME"]
    app = QApplication(argv)
    filename, _ = QFileDialog.getOpenFileName(caption="Load Input File",
                                              directory=default_dir,
                                              filter="*txt")
    app.exit()
    return filename


if __name__ == "__main__":

    #---------------------------Files reading----------------------------------

    # inputFile_path = open_file("./")

    inputVariables = Utility.read_inputFile("./inputFile.txt")

    elementList = Utility.molToElemList(inputVariables["molecule"])
    elementParameters = Utility.read_parameters(
        elementList, inputVariables["elementParamsPath"])
    elementPosition = Utility.read_xyz_file(inputVariables["xyzPath"])

    Q, I_Q = Utility.read_file(inputVariables["dataFile"])
    Qbkg, Ibkg_Q = Utility.read_file(inputVariables["bkgFile"])

    # plt.plot(Q, I_Q)
    # plt.plot(Qbkg, Ibkg_Q)
    # plt.show

    #--------------------Preliminary calculation-------------------------------