Example #1
0
    def paraxialGaussian(self):

        # get input from text boxes
        self.lambda0 = convertUnitsStringToNumber(self.ui.wavelength.text(), "m")
        self.w0 = convertUnitsStringToNumber(self.ui.waistSize.text(), "m")
        self.w0_z = convertUnitsStringToNumber(self.ui.waistPosition.text(), "m")
        self.zR = math.pi * self.w0 ** 2 / self.lambda0  # horiz. Rayleigh range [m]

        # instantiate the laser pulse
        self.myPulse = hermite.RbGaussHermiteMN(self.lambda0, self.w0, self.w0, 0.0)

        # load up the coefficients
        mCoefs = np.zeros(8)
        nCoefs = np.zeros(8)
        for iLoop in range(8):
            mCoefs[iLoop] = float(self.ui.ghTable.item(iLoop, 0).text())
            nCoefs[iLoop] = float(self.ui.ghTable.item(iLoop, 1).text())

        self.myPulse.setMCoef(mCoefs)
        self.myPulse.setNCoef(nCoefs)

        # update flag accordingly
        self.pulseInitialized = True

        # generate the plots
        self.refreshPlots()
Example #2
0
def test_unit_conversion():
    # Simple test
    a = '12 in'
    ac = convertUnitsString(a, 'km')
    b = '1 ft'
    bc = convertUnitsString(b, 'km')
    assert ac == bc

    # Compound test
    a = '60 mi/hr'
    ac = roundSigFig(convertUnitsStringToNumber(a, 'm/s'), 10)
    b = '88 ft/sec'
    bc = roundSigFig(convertUnitsStringToNumber(b, 'm/s'), 10)
    assert ac == bc

    # Invalid test
    a = '4 score'
    with pytest.raises(ValueError):
        convertUnitsString(a, 'years')

    # Higher dimension test
    a = 16.7 # km^2, 
    ac = convertUnitsNumberToString(a, 'km^2', 'mi^2')
    b = '6.44790604766 mi^2'
    bc = convertUnitsString(b, 'mi^2')
    assert ac == bc

    # Angle test
    a = 3 # radians
    ac = roundSigFig(convertUnitsNumber(a, 'rad', 'deg'), 10)
    b = 3*180/pi # 3 rad in degrees
    bc = roundSigFig(b, 10)
    assert ac == bc

    # Compound units
    a = "9.8 m/s^2"
    ac = roundSigFig(convertUnitsStringToNumber(a, "ft/ms^2"), 6)
    b = 3.21522e-5 # ft / (ms^2)
    assert ac == b

    # Inverse units
    a = "10 1/s"
    ac = convertUnitsString(a, 'Hz')
    b = "10.0 Hz"
    assert ac == b

    a = "1 1/ns"
    ac = convertUnitsString(a, 'GHz')
    b = "1.0 GHz"
    assert ac == b
Example #3
0
    def saveToSDDS(self, sddsFileName=None):
        if not sddsFileName:
            sddsFileName = getSaveFileName(self, "sdds")
            if not sddsFileName:
                return

        with open(sddsFileName, "w"):
            return

        # make sure the top-level parameters are up-to-date
        self.designMomentumEV = convertUnitsStringToNumber(self.ui.designMomentum.text(), "eV")
        self.totalCharge = convertUnitsStringToNumber(self.ui.totalCharge.text(), "C")

        # create local pointer to particle array
        tmp6 = self.myBunch.getDistribution6D().getPhaseSpace6D().getArray6D()

        mySDDS = sdds.SDDS(0)
        mySDDS.description[0] = "RadTrack"
        mySDDS.description[1] = "Copyright 2013-2014 by RadiaBeam Technologies. All rights reserved."
        mySDDS.parameterName = ["designMomentumEV", "totalCharge", "eMassEV"]
        mySDDS.parameterData = [[self.designMomentumEV], [self.totalCharge], [self.eMassEV]]
        mySDDS.parameterDefinition = [
            ["", "", "", "", mySDDS.SDDS_DOUBLE, ""],
            ["", "", "", "", mySDDS.SDDS_DOUBLE, ""],
            ["", "", "", "", mySDDS.SDDS_DOUBLE, ""],
        ]
        mySDDS.columnName = ["x", "xp", "y", "yp", "s", "dp"]
        mySDDS.columnData = [
            [list(tmp6[0, :])],
            [list(tmp6[1, :])],
            [list(tmp6[2, :])],
            [list(tmp6[3, :])],
            [list(tmp6[4, :])],
            [list(tmp6[5, :])],
        ]

        if False:
            print(" ")
            print(" Here is mySDDS.columnData[:]:")
            print(mySDDS.columnData)

        mySDDS.columnDefinition = [
            ["", "m", "", "", mySDDS.SDDS_DOUBLE, 0],
            ["", "rad", "", "", mySDDS.SDDS_DOUBLE, 0],
            ["", "m", "", "", mySDDS.SDDS_DOUBLE, 0],
            ["", "rad", "", "", mySDDS.SDDS_DOUBLE, 0],
            ["", "m", "", "", mySDDS.SDDS_DOUBLE, 0],
            ["", "rad", "", "", mySDDS.SDDS_DOUBLE, 0],
        ]
        mySDDS.save(sddsFileName)
Example #4
0
    def validate_momentum(self):
        """Ensure the momentum value is valid"""
        if self.bunch_source_manager.is_momentum_required():
            try:
                momentum = float(self.ui.momentumLineEdit.text())
            except ValueError:
                try:
                    momentum = convertUnitsStringToNumber(
                        self.ui.momentumLineEdit.text(), 'MeV')
                except ValueError:
                    self.show_warning_box('Unable to parse momentum')
                    self.ui.momentumLineEdit.setFocus()
                    return None
        else:
            bunchTab = self.bunch_source_manager.get_tab_widget()
            bunchTab.generateBunch() # make sure any new settings get read

            try:
                momentum = convertUnitsNumber(
                    bunchTab.myBunch.getDesignMomentumEV(), 'eV', 'MeV')
            except ValueError:
                self.show_warning_box(
                    'Invalid momentum value on Bunch Tab')
                return None
        return momentum
Example #5
0
 def getParameter(self, pName):
     index = self.parameterNames.index(pName)
     val = self.data[index]
     try:
         return convertUnitsStringToNumber(val, self.units[index])
     except ValueError:
         return rpn(val)
Example #6
0
    def componentLine(self):
        sentence = [(param, str(convertUnitsStringToNumber(datum, unit))) \
                for param, datum, unit in \
                zip(self.parameterNames, self.data, self.units) if datum]
        sentence = ', '.join(['='.join(phrase) for phrase in sentence])

        return self.name + ':    ' + type(self).__name__ + ', ' + sentence
Example #7
0
    def saveToCSV(self, fileName=None):
        if not fileName:
            fileName = getSaveFileName(self, "csv")
            if not fileName:
                return

        with open(fileName, "w"):
            return

        # make sure the top-level parameters are up-to-date
        self.designMomentumEV = convertUnitsStringToNumber(self.ui.designMomentum.text(), "eV")
        self.totalCharge = convertUnitsStringToNumber(self.ui.totalCharge.text(), "C")

        # create local pointer to particle array
        tmp6 = self.myBunch.getDistribution6D().getPhaseSpace6D().getArray6D()
        numParticles = tmp6.shape[1]

        # create a header to identify this as a RadTrack file
        h1 = "RadTrack,Copyright 2012-2014 by RadiaBeam Technologies LLC - All rights reserved (C)\n "
        # names of the top-level parameters
        h2 = "p0 [eV],Q [C],mass [eV]\n "
        # values of the top-level parameters
        h3 = str(self.designMomentumEV) + "," + str(self.totalCharge) + "," + str(self.eMassEV) + "\n "
        # label the columns
        h4 = "x,xp,y,yp,s,dp\n "
        # specify the units
        h5 = "[m],[rad],[m],[rad],[m],[rad]"
        # assemble the full header
        myHeader = h1 + h2 + h3 + h4 + h5
        # write particle data into the file
        #   The following ugliness is used to accommodate savetxt()
        #   There is probably a better way...
        f6 = np.zeros((numParticles, 6))
        f6[:, 0] = tmp6[0, :]
        f6[:, 1] = tmp6[1, :]
        f6[:, 2] = tmp6[2, :]
        f6[:, 3] = tmp6[3, :]
        f6[:, 4] = tmp6[4, :]
        f6[:, 5] = tmp6[5, :]
        np.savetxt(fileName, f6, fmt="%.12e", delimiter=",", comments="", header=myHeader)
Example #8
0
    def mirrorWithHole(self):
        # toggle the corresponding flag
        self.externalFields = True

        # get input from text boxes
        self.lambda0 = convertUnitsStringToNumber(self.ui.wavelength.text(), "m")
        self.w0 = convertUnitsStringToNumber(self.ui.waistSize.text(), "m")
        self.w0_z = convertUnitsStringToNumber(self.ui.waistPosition.text(), "m")
        self.zR = math.pi * self.w0 ** 2 / self.lambda0  # horiz. Rayleigh range [m]

        # load up the x,y locations of the mesh
        self.xMin = -4.0 * self.w0
        self.xMax = 4.0 * self.w0

        self.yMin = self.xMin
        self.yMax = self.xMax

        self.numPts = 64
        self.nCells = self.numPts ** 2

        self.xArr = np.zeros(self.numPts)
        for iLoop in range(self.numPts):
            self.xArr[iLoop] = self.xMin + iLoop * (self.xMax - self.xMin) / (self.numPts - 1)

        self.yArr = np.zeros(self.numPts)
        for jLoop in range(self.numPts):
            self.yArr[jLoop] = self.yMin + jLoop * (self.yMax - self.yMin) / (self.numPts - 1)

        self.xGrid = np.zeros((self.numPts, self.numPts))
        self.yGrid = np.zeros((self.numPts, self.numPts))

        for iLoop in range(self.numPts):
            for jLoop in range(self.numPts):
                self.xGrid[iLoop, jLoop] = self.xMin + iLoop * (self.xMax - self.xMin) / (self.numPts - 1)
                self.yGrid[iLoop, jLoop] = self.yMin + jLoop * (self.yMax - self.yMin) / (self.numPts - 1)

        # Create transverse field profile (#3 elliptical Gaussian donut)
        self.ExGridExternal = np.zeros((self.numPts, self.numPts))
        self.wx3 = 2.0 * self.w0
        self.rad1 = 1.0 * self.w0
        self.rad2 = 2.0 * self.w0
        for iLoop in range(self.numPts):
            for jLoop in range(self.numPts):
                xArg = self.xArr[iLoop]
                yArg = self.yArr[jLoop]
                rArg = math.sqrt(xArg ** 2 + yArg ** 2)
                rFactor = 1.0
                if rArg <= self.rad2:
                    rFactor = 0.5 + 0.5 * math.cos(math.pi * ((rArg - self.rad1) / (self.rad2 - self.rad1) - 1.0))
                if rArg <= self.rad1:
                    rFactor = 0.0
                self.ExGridExternal[iLoop, jLoop] = (
                    rFactor * math.exp(-(xArg / self.wx3) ** 2) * math.exp(-(yArg / self.wx3) ** 2)
                )

        # generate the xy plot
        canvas = self.ui.xyPlotExtFields.canvas
        canvas.ax.clear()

        myPlotUtils = radtrack.plot.RbPlotUtils.RbPlotUtils()
        levels = myPlotUtils.generateContourLevels(self.ExGridExternal)
        canvas.ax.contourf(
            self.xGrid * convertUnitsNumber(1, "m", self.unitsXY),
            self.yGrid * convertUnitsNumber(1, "m", self.unitsXY),
            self.ExGridExternal,
            levels,
            extent="none",
            aspect="equal",
        )
        canvas.ax.xaxis.set_major_locator(plt.MaxNLocator(self.numTicks))
        canvas.ax.yaxis.set_major_locator(plt.MaxNLocator(self.numTicks))
        canvas.ax.set_xlabel("x [" + self.unitsXY + "]")
        canvas.ax.set_ylabel("y [" + self.unitsXY + "]")
        canvas.ax.axis(
            [
                self.xMin * convertUnitsNumber(1, "m", self.unitsXY),
                self.xMax * convertUnitsNumber(1, "m", self.unitsXY),
                self.yMin * convertUnitsNumber(1, "m", self.unitsXY),
                self.yMax * convertUnitsNumber(1, "m", self.unitsXY),
            ]
        )
        if self.plotTitles == True:
            canvas.ax.set_title("slice: quadratic square; at z={0:4.2f} [{1}]".format(0.0, self.unitsZ))

        canvas.fig.tight_layout()
        canvas.fig.set_facecolor("w")
        canvas.draw()