Category Archives: Python

Computer Languages and High Energy Physics

A common question that people who are thinking about going into physics is “What programming language should I learn?”

This question doesn’t necessarily have a good answer. Really, the answer depends not only on what subfield you are interested in but also what experiment you will work on. In the field of experimental high energy physics (i.e. particle physics) there are three languages that are by far the most useful for day-to-day work.

They are: C++, Fortran, and Python.

C++ (or sometimes just C) and Fortran are used because they are fast and already have enormous libraries of optimized code, allowing you to use things like FFTW (Fastest Fourier Transform in the West) and the GSL (GNU Scientific Library). These are older languages and not the easiest to code but allow a lot of flexibility. If you’re doing computationally intensive work, chances are you’re working with one of these languages. In HEP, Fortran is mostly found in older libraries, many of which are being replaced by newer C++ versions. Thus, you get things like PAW, GEANT3, and Garfield – Fortran-based programs found in CERNLIB – being replaced by ROOT, GEANT4 and Garfield++, which are C++ based. Fortran is still used quite extensively, though, and many simulation toolkits continue to be maintained in Fortran. I’m not an expert on what is used in high energy theory, but I believe Fortran is also one of the most common languages there as well (again, due to the huge set of libraries available for scientific computing and due to it remaining one of the fastest languages). C++ has a lot of nice features – it’s always been object-oriented, it includes templates and the STL, etc., and is much newer than Fortran (there aren’t really any obvious vestiges of punch-card programming in C++!).

Python is becoming more and more popular for high level programming. While it’s too slow for many computations, it is a very nice scripting language. You can quickly create programs that will work without needing to deal with Makefiles and compilers. For example, you could create a bunch of C++ programs to process and analyze a dataset using a Python program to control everything. Furthermore, you can even create Python bindings for C++ code (and some other languages too), allowing you to call your C++ functions inside a Python program. This lets you run everything in Python so that the computationally-intensive parts were compiled using C++ code and the rest is just Python.

Another big advantage of these languages is that they are free. Most people in HEP use the GNU compilers gcc, g++, gfortran, etc. to compile the code. These tools and many of the scientific libraries (like the ones I mentioned above) are also free. This is in stark contrast to languages like Matlab and Mathematica, popular in undergraduate coursework and in some other fields but which can also cost hundreds of dollars per user per year. The same is true of IDL, which is popular among astronomers. Python has NumPy and SciPy which mimic much of the functionality of Matlab. Common languages like Java, Perl, and Ruby may be encountered but aren’t used very often by particle physicists. If you’re going to be working with websites or databases, you might also run into SQL, Javascript, PHP, etc, though these are more for “service work” – keeping the experiment running – rather than an actual physics analysis.

Advertisements

Making LaTeX Equations

On Mac, there is a program called LaTeXiT, which will create images of LaTeX equations that can be easily imported into other documents. Linux has a similar program called klatexformula. These allow you to avoid writing an entire document just to get the image of a single formula.

I’ve created a very compact program to do something similar, but without a lot of the fancy features like drawing the image or saving history. It’s a barebones version that will just create an image in one of a number of file formats. Here it is:

#! /usr/bin/python
from Tkinter import *
import ScrolledText
import signal
import sys
import os
class Dialog:
  def __init__(self,parent):
    self.filelist = []
    cur_row = 0
    root = self.root = parent
## File name
    Label(root, text="File name (no extension)").grid(padx=5,row=cur_row, sticky=W)
    self.filename = Entry(root)
    self.filename.grid(padx=5,row=cur_row,column=1,sticky=W+E)
## Format
    cur_row = cur_row+1
    Label(root,text="Format").grid(row=cur_row,sticky=W,padx=5)
    self.form = StringVar(root)
    self.form.set("png")
    option=OptionMenu(root,self.form,"png","pdf","ps","eps","jpg","svg",
"tif")
    option.grid(padx=5,row=cur_row,column=1,sticky=W+E)
## Font size
    cur_row = cur_row+1
    Label(root,text="Font Size").grid(row=cur_row,sticky=W,padx=5)
    self.fontsize = StringVar(root)
    self.fontsize.set("normalsize")
    sizeopt=OptionMenu(root,self.fontsize,"tiny","scriptsize",
"footnotesize","small","normalsize","large","Large","LARGE","huge","Huge")
    sizeopt.grid(padx=5,row=cur_row,column=1,sticky=W+E)
#Environment
    cur_row = cur_row+1
    Label(root,text="Environment").grid(row=cur_row,sticky=W,padx=5)
    self.enviro = StringVar(root)
    self.enviro.set("Equation")
    envopt=OptionMenu(root,self.enviro,"Equation","Align")
    envopt.grid(padx=5,row=cur_row,column=1,sticky=W+E)
## Equation
    cur_row = cur_row+1
    Label(root, text="Write Equation in LaTeX Format").grid(row=cur_row,padx=5,columnspan=3)
    cur_row = cur_row+1
    self.equation = ScrolledText.ScrolledText(root,wrap=WORD,width=40,height=10)
    self.equation.grid(padx=5,columnspan=3,row=cur_row,sticky=W+E+N+S)
    root.grid_rowconfigure(cur_row,weight=1)
    root.grid_columnconfigure(0,weight=1)
# Run button
    b = Button(root,text="RUN",command=self.run)
    cur_row = cur_row+1
    b.grid(row=cur_row,sticky=W+E)
# Dialog
    self.errvar = StringVar()
    self.rundialog = Label(root,textvariable=self.errvar)
    self.rundialog.grid(padx=5,row=cur_row,column=1,sticky=W+E)
# Quit
    quit = Button(root,text="QUIT",command=self.quit)
    quit.grid(padx=5,row=cur_row,column=2,sticky=W+E)
  def quit(self):
    self.cleanup()
    self.root.destroy()
  def run(self):
    theEquation = self.equation.get("1.0",END+'-1c')
    if theEquation is "":
      self.errvar.set("Set Equation!")
      return
    theFile = self.filename.get()
    if theFile is "":
      self.errvar.set("Set Filename!")
      return
    extension = self.form.get()
    environment = self.enviro.get()
    size = self.fontsize.get()
    texfile = open(theFile+".tex","w")
    texfile.write("\\documentclass[varwidth=true,border=10pt]{standalone}\n")
    texfile.write("\\usepackage{amsmath}\n")
    texfile.write("\\usepackage{amssymb}\n")
    texfile.write("\\begin{document}\n")
    texfile.write("\\"+size+"\n")
    texfile.write("$$\n")
    if environment == "Align":
      texfile.write("\\begin{aligned}\n")
    texfile.write(theEquation)
    if environment == "Align":
      texfile.write("\\end{aligned}\n")
    texfile.write("$$\n")
    texfile.write("\end{document}")
    texfile.close()
    if theFile not in self.filelist:
      self.filelist.append(theFile)
    err = os.system("pdflatex -halt-on-error -interaction=nonstopmode "+theFile+".tex")
    if err:
      self.errvar.set("LaTeX Error!")
      return
    if extension != "pdf":
      if extension == "jpg":
        extopt = "jpeg"
      elif extension == "tif":
        extopt = "tiff"
      else:
        extopt = extension
    os.system("pdftocairo -"+extopt+" "+theFile+".pdf "+theFile)
    os.system("mv "+theFile+"-1."+extension+" "+theFile+"."+extension)
    os.system("rm -f "+theFile+".pdf")
    self.quit()
  def cleanup(self):
    for f in self.filelist:
      os.system("rm -f " + f+".tex "+f+".aux "+f+".log")
if __name__== "__main__":
  root = Tk()
  root.title("Latex Equation Creator")
  root.geometry("400x400")
  d = Dialog(root)
  root.wait_window(d.root)

It works using Ubuntu and TeX Live 2014 and is written in python 2.7 with the TkInter package. You might need to correct some indentation and line-wrapping problems if you try to use this html version.