Dec 13, 2012

Screenshots for configuration of FFTW3 in C++ (Windows)


When you download the zip file from “http://fftw.org/install/windows.html”,



By default, the zip file is like this (I use 64-bit version):






First thing you should do is to generate .lib files for these .dll files. Refer to the post here:
(notice in this post also have information for debug in case you find this problem)
Then copy them to the same folder which should looks like:

Copy this folder to your project’s folder (actually you can put it anywhere).
Here begins the screen shots of configuration:

1 Open the property configuration for present project. Choose “General” under “C/C++” option tab.

2 add the .dll file’s directory by click “Additional Include Directories”:

3 under the “Linker/General” option, choose “Additional Library Directories”

4 add the directory of your  .dll file here:

5 add the .lib files’ names under the “Linker/Input” option here:

6 make sure you’ve input all the .lib files you want to use;


Now you should be able to see the external header file under “External Dependencies” :



And include it above the other library:


Done.


In my code, I begin to use it like this:


You should refer to the manual of FFTW3 for the use of it.


·         You can choose “Optimization for running the code” to save running time if you don't need debug info.
·         

Dec 8, 2012

C++ note (1) 20121208

IDE Integrated Development Environment

Editor
The Compiler
    covert source code into object code (.obj)
The Linker
    weld everything into an executable whole
The Libraries
    a collection of pre-written routines
        Standard C++ Library
        Microsoft Foundation Classes (MFC)
        Windows Forms

Projects and Solutions
    A project is a container for all things that make up a program of some kind. All files are stored in the project folder.
    Detailed information about the project is stored in an XML file (.vcxproj).
 
    A solution is a mechanism for bringing together all the programs and other resources that represent a solution to a particular data-processing problem. A solution may include several projects or a single project. Usually, a solution has only one project, where usually it has the same name as project, unless otherwise.
    .sln -- information about the projects in the solution
    .suo -- user options
    .sdf -- records data about Intellisense for the solution, which is the facility that provides autocompletion and prompts you for code in the Editor window as you enter it.
    .opensdf -- this file exists only while the project is open.

Building the solution
After you building the solution, in case of a Console Application, a few files would be generated:
    under solution name folder, a debug sub-folder would be generated
        .exe -- program in executable form
        .ilk used by the linker when rebuild the project. This avoids the need of relink everything each time you change the program
        .pdb -- contains debugging information when execute the program in debug mode
    under the project name folder there's another 'debug' folder, too. It has a large number of files that were created during the build process.

Debug and Release version of program
    When you  create a new project workspace, two versions of the application would be generated.
    Debug version -- includes additional information that helps you debug the program
    Release version -- no debug information and has the code-optimization options for the compiler.

Shortcuts
    F7 --  build the program
    Ctrl + F5 -- execute the program

Create an Empty Console Project
    stdafx.h -- head file being created in an default Win32 Console Application. This is a mechanism for making the compilation process more efficient when there are lots of files in a program.
    By default, the project options will be set to use Unicode libraries, which makes use of a non-standard name for the main function in the program. In order to use standard native C++ in your console programs, you need to switch off the use of Unicode libraries.( Project -> Properties -> Configuration Properties -> General -> Character Set -- 'Not Set' ).
    _tmain -- is defined to be either 'main' or 'wmain' (in the header tchar.h), depending on whether or not the program is defined to be to use Unicode characters. In standard of C++/IEC programs start execution in a function called main(), so you need to change the Character Set property value for native C++ to Not Set.

Create a CLR Console Project
After you create a CLR console project, there are no options for a CLR project.
A couple of files in the virtual Resource Files folder:
    .ico -- stores an icon for the application that is displayed when the program is minimized
    .rc -- records the resources for the application
AssemblyInfo.cpp -- an assembly consists of code and resources that forms a functional unit. Every CLR program consists of one or more assemblies. an assembly is a fundamental building block in all CLR programs.






Jul 4, 2012

Master Thesis Revise Log

2012-7-4 Chp3 by Takayama

General comments:

Delete most of coordinate conjunctions, such as However, ....
Caption of figures is too poor. More explanation is reqyuired.

●This chapter should begin as

"The KEK Digital Accelerator consists of ........."

●Requirement of the chopper is not related to saturation of the
induction cells.
●We don't call "Einzel lens chopper" to distinguish from the
conventional one.
●Explanation of LEBT is too poor.
●Beta function and Dispersion function should be unfamiliar to TokyoTech
staffs. You need to put some explanation for them.
●What is the under curve in Figure 3.14? Figure 3.13 and 14 can be
combined.
●Limitation of the present induction acceleration system should be
correctly classified.
(1) Volatage
1-1 DC voltage (you describe)
1-2 Maximum output voltage
(2) Pulse length (from voltage droop)
(3) Rep-rate
●Figure 3.24 is deleted.

Ken Takayama

May 31, 2012

What needs to be done for Simulation

1 separate the plot module after the simulation end at t_max or turn_max

2 use OpenMP for parallel computation with omp.h head file

3 calculate the emittance for x-x' and center of x-direction

May 23, 2012

notice the INT_MAX in your code!

no details, but be careful ! If necessary use long long int instead.

May 20, 2012

How to optimize your code in VC++

Last time I have talked about the optimization of the running code but didn't show how to do that. Here it is:


  • open you project's property and change to the C++/C


make sure that "Debug Information Format" is chosen to be "Program Databas(/Zi)

  • change to "Optimization" tab, 

choose Full Optimaization(/Ox) or Maximize Speed(/O2).



  • change to " Code Generation" tab


choose "Default" for "Basic Runtime Checks"

A word of caution, optimization is good for running but the debug information is hard to understand if you're in the process of debugging your code. So this optimization should apply after you find no problems in building and want to run the program for test.

May 17, 2012

array vs vector

Every beginner is struggling doing something that is so simple to others.

Once you know it, you will say to yourself: I did know it should be something simple like this.

Specify the size of array at run-time,dynamically

in C++, sometimes(for me, most of the times), we don't know how long should an array should be. If that is the case, we can do the following:

float *pTable;
int n = 100;
pTable = new float[n];

The point is that one of the common use of pointer is to allocate memory in leap . Then at run-run, you can choose the size based on the need. But once you use new, don't forget to use delete to free the memory.
delete [ ] pTable;

And notice that we also have a STL container called std::array, (include it with #include<array>), it adds useful member functions and iterators to it. So it convenient to use. But still, you need to use pointer to get a run-time specified size of it.
OK, now we see that the built-in array have some drawbacks and even for the std::array we have to specify the size of it with a constant. Why don't we just use vector, which does all the tedious work for us? "I thought for a computation intense program, array is faster than vector," you will think like this as I did. However, this is not true!
Read this link for this answer then you will not waste you time in figuring out those tedious things related to array, just go with vector and finish your work.

Then here is the conclusion: just go with vector


  1. Nearly all of the time, you should choose vector instead of array( built-in or std::array). Spend those saved time in programming.
  2. the vector performs less efficient only when you need change its size frequently(which makes it reallocate the memory). If that's not the case, their performance almost the same.
  3. the compile spends a lot of extra work in range-checking or similar thing in debugging. Once you got your program right, you can use a optimized build and right settings (removing the STL debugging).


May 16, 2012

c++ read in file for initialization

two things you should know:

  1. getline read in a single line with "\n" delimiter by default, you can specify the delimiter
  2. >> will automatically skip white space and choose the right type for you

A stardard example

// ini.txt
numberofTest: 100000
kickPerTurn: 20
// code segment
ifstream ini_para("ini_parameters.txt");
if( ini_para.fail() )
cerr <<" failed to open ini_parameters.txt" ;
string dummy_string;
getline(ini_para,dummy_string,':');
         // it's import that you use ':' instead of ":" 
ini_para >> numberofTest;
cout << "numberofTest read as: " << numberofTest <<endl;
getline(ini_para,dummy_string,':');
ini_para >> kickPerTurn;
cout << "kickPerTurn read as: " << kickPerTurn <<endl;
     
        ini_para.close();
A similar discussion could be found example on cplusplus.com.


May 14, 2012

Two things today


  1. Test the micro-bunching structure with momentum modulation
  2. Finish the code implementing the FFT Longitudinal space-charge force

How to call Gnuplot from C++

When I have do the simulation to our physics problem, I have many data files that I want to visualize. It's not an easy work, if you are a new C++ user like me. After searching around the internet, finally I got the solution pretty nice. Here is how.

1 download and intall

go to  gnuplot.info to download the windows installer and install it (The newest edition is 4.6 till this document). Make sure that you choose "add PATH to my system" in the process of installation, or you have to add by your own. (Thanks the gnuplot team adding this for us).

2 create a general purpose head file

create a new .h file with this following content(or you can download it here):

#ifndef GNUPLOT_H_
#define GNUPLOT_H_
#include <string>
#include <iostream>
using namespace std;
class Gnuplot {
public:
Gnuplot() ;
~Gnuplot();
void operator ()(const string & command);
// send any command to gnuplot
protected:
FILE *gnuplotpipe;
};
Gnuplot::Gnuplot() {
// with -persist option you will see the windows as your program ends
//gnuplotpipe=_popen("gnuplot -persist","w");
//without that option you will not see the window
 // because I choose the terminal to output files so I don't want to see the window
 gnuplotpipe=_popen("gnuplot","w");
if (!gnuplotpipe) {
cerr<< ("Gnuplot not found !"); }
}
Gnuplot::~Gnuplot() {
fprintf(gnuplotpipe,"exit\n");
_pclose(gnuplotpipe);
}
void Gnuplot::operator()(const string & command) {
fprintf(gnuplotpipe,"%s\n",command.c_str());
fflush(gnuplotpipe);
// flush is necessary, nothing gets plotted else
};
#endif

3 use the head file and plot

 now you have a class of gnuplot, so you can initialize it with object and send the command directly to gnuplot. If you don't know what I mean, check the example I use to test under Windows(example.cpp)

#include <iostream>
#include "gnuplot.h"
using namespace std;
int main(){
Gnuplot plot;
plot("plot sin(x)") ;
system("pause");
plot("plot cos(x)") ;
system("pause");
return 0;
}

Others:

The good side is that you can customize what you want to plot and make it automatically done for you.
The bad side is that it is the same usage as gnuplot itself. I mean, if you have to plot the simulation results, you have to output them then read in and plot the graph out. If you concerns only on the graph instead of the output data files, you will find that the most time-consuming thing for C++ is output files. If you have better solution for this( directly plot with a data structure), please let me know. I know there's some pipe written for this but they just don't work for me. Maybe you have better suggestion. Thanks.

May 13, 2012

Use FFTW in C++

Linux/Unix

in Ubuntu it's very easy, just compile the source, then link the library to the project in project property. I use ellipse to write the program, no problem with that.

Windows

I never succeed in linking the fftw library in Microsoft Visual C++ Express 2010, though my friend told me there's no problem with that. I use 64-bit Windows 7.

there're basically three things you need to do if you have the same environment as me:
all you need is the following: fftw3.h, three .dll files(libfftw3-3.dll,libfftw3l-3.dll,libfftw3f-3.dll), three .def files(libfftw3-3.def,libfftw3l-3.def,libfftw3f-3.def).

1 generate the .lib files

In fact, .lib files is necessary but not included in the .zip files we download from fftw.org. That's because it's better to compile for yourself what you need (-- at least let's think in this way, I know some of you don't agree with me on this point).
open cmd.exe, then direct to the folder where your lib.exe is, for example, here is mine with a default installation of VC++ Express:
 C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin
(oh, wait a moment, you should copy the following files from another folder to the \bin folder before you can proceed, I guess--at least for me it's like this:
C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE
msobj100.dll
mspdb100.dll
mspdbcore.dll
mspdbsrv.exe
if you are using 2011, I think it's something like msobj110.dll )
 now copy those three .def files into the \bin folder.
then use lib.exe setup under cmd environment to generate the three .lib files in compatible to your system(change your machinetype, 64-bit windows is x64, 32-bit is x86)
lib /machine:x64 /def:libfftw3-3.def
lib /machine:x64 /def:libfftw3f-3.def
lib /machine:x64 /def:libfftw3l-3.def
OK, we're finished with three .lib files. (I recommend you generate another 32-bit like me in case you may use them later) Move the three .lib files out to the original folder where it should be, for example, here I just copy them back to the same folder as  fftw3.h (in fact, you just find a place you find convenient).


2 link the library before you can use #include<fftw3.h> in your code:


copy the three .dll files into the default folder of your project ( the same as .vcxproj and .vcxproj.filters, default for your code). (In fact, I just copy one, because I only use this one: libfftw3-3.dll. And I also have a folder like "\fftw-3.3.1-dll64" here to contain my .h file and .lib files)
open the properties of you project, under the "C/C++" option, chose "general", then add the path of you fftw3.h files(should be in a folder) into "Additional Include Directories"
change to the "Linker" option and choose "general", add the .lib files path(could be the same folder) to the "Additional Library Directories"
under the  "Linker" option and choose "input", add the following items to the "Additional Dependencies":

libfftw3-3.lib
libfftw3l-3.lib
libfftw3f-3.lib

3 (if you're using 64-bit windows as me) change your project to be compiled as 64-bit as you use 64-bit compiled .lib files to the .dll files.
(I get this help from stackflow:
http://stackoverflow.com/questions/1865069/how-to-compile-a-64-bit-application-using-visual-c-2010-express Remind you that you should install Windows7.1SDK if you want to debug as 64-bit with Express 2010, with other Visual Studio I think you have x64 debugger with you )
However, I didn't succeed with that as I mentioned at the beginning. I tried 32-bit .lib files and it didn't work either. As frustrated as me, I installed the trial version of Visual Studio 2011, where I got the x64 debug on its installation and it's easy to get it done like this( almost same as the above link):
Go to Properties of your project. On the top of the dialog box there will be a "Configuration" drop-down menu. Make sure that selects "All Configurations." There will also be a "Platform" drop-down that will read "Win32." Finally on the right there is a "Configuration Manager" button - press it. In the dialog that comes up, find your project, hit the Platform drop-down, select New, then select x64. When you return to the Properties dialog box, the "Platform" drop-down should now read "x64."

(
By the way, if you have problem in debugging. Follow this:
 How to rightly set-up debug:
1) Goto your Project Properties
2) On the left expand "Configuration Properties"
3) Expand "C/C++"
4) On the left, Select "General"
5) On the right, change "Debug Information Format" to "Program Database For Edit And Continue (/ZI)"
5) On the left, Select "Optimization"
6) On the right, change "Optimization" to "Disabled (/Od)"
7) On the left, expand "Linker"
8) On the left, select "Debugging"
9) On the right, change "Generate Debug Info" to "Yes"
10) Click ok
11) Set your breakpoints
12) Rebuild your application
Also when running your application use Ctrl+F5 to build and run it, this keeps the console window open long enough for you to see your output.
)

OK, well done, now you can #include<fftw3.h> and test an example. The best one is on the fftw manual, check it instead of the Internet.

The Mathematica Documents

Beam Lattice


  • ring Lattice: finished and justified(two methods)
  • LEBT lattice: almost finished

(both of them could be compared with Madx's output)

Experimental Data Analyzing

  • Bdc results: finished. with FFT to get the period and a manipulate to get a dynamic view turn by turn
  • Bac results: no

Others:


  • FFT method for LSC(part II)--needed to be improved
  • part I needed to be write

Period for 200kV Helium 1 plus in DA

 The difference between calculated one and experimental one

calculation

For this calculation, at first glance, it is as simple as C0/v. Yes, you can say that only if:
  • correct circumference of the ring
  • correct rest mass of Helium
  • properly choose the right constant for light speed, proton mass, neutron mass, electron charge
  • the kinetic energy for the beam is precisely as 200 kv
After I choose the  following parameters(as used in harada's table calculation)
  • C0 = 37.71 m
  • const double lightSpeed = 2.99792458e8 m/s
  • const double electronCharge = 1.60217646e-19 C
  • const double protonMass = 1.672621e-27 kg
  • const double NeutronMass = 1.674927e-27 kg
for 200kv Helium 1+, circumference of the ring taken as 37.71m, 
lightSpeed = 2.99792458*10^8;
electronCharge=1.60217646*10^-19;
protonMass=1.672621*10^-27;
NeutronMass=1.674927*10^-27;
HeliumRest = 2*(NeutronMass+protonMass)*lightSpeed^2/electronCharge
ringLength=37.71;
extV=2*10^5;
gamma=extV/HeliumRest+1
beta=Sqrt[1-1/gamma^2]
T=ringLength/(beta*lightSpeed)
Output:
 beta = 0.0103197
T=12.189 us
if calculated with (as in Harada's "TsGEN3_20111025"):

  •  m0 = A * 1.6726231e-27 
  • A = 4
  • gamma = 1.0 + kinetic_energy * e / ( m0 * c * c )
  • beta = sqrt( 1 - 1/(gamma*gamma) )

the output is the same.

energy error

if we assume some energy differece at the injection, for example, 201kV, then the result is
T=12.1586 us

method error and ring length error

if we use atomic weight of helium as 4.002602 and atomic mass unit corresponding to energy in eV as 931.494061×10^6, the result is
T=12.1446 us
further more, if the change the ring length to be 37.75(4 cm longer)
T=12.1575 us

experiment

However, after doing FFT analysis to the bunch signal from the experimental data, the period is(2011116,1206,1222),:
T_experiment=12.1579 us
the difference is about: ( T - T_experiment )/T_experiment = 0.26%. This is a difference of 31 ns. Provided that the rise time of our Vbb is around ~80, or ~100 ns, in the experiment with Vbb this might be a problem.(in fact it may be good for commissioning, because the bunch tends to  "arrive later" when the B field is rising without acceleration to the beam.

others

I notice that for the 20111116 data, we did the experiment for different bunch length and different beam current. But the FFT analysis suggests that the period is changing as time goes by. This may suggested that the voltage is not so consistent with the B-field.

A better way is to do FFT to the part of the data ( for example, every 5 turns) until the time end(for example, 4ms as we usually use), then we can get a T changing along the time.

Strictly speaking, we cannot keep the extraction energy precisely every time we do the beam commissioning. However, as we can see by different date, the period given by the experiment is somehow repeat itself. With this we can safely say they're unnoticeable difference on the injection energy.

Note that if the injection energy is different from the what it needs to be with the B field, the period will change as time goes on.

conclusion at this momentum

as discussed above, use the atomic weight and a length of 37.75m is closer to the experiment result, if the result is reliable.




May 11, 2012

Barrier voltages could be detrimental to beam commissioning

The formal scheme is that we trigger the Vac and Vbb voltage with a relative delay to the referential signal.

However, as the by the default idea of pulse density control (with or without threshold for accumulated required voltage), in the phase space of  (t, dp_p), the bunch would travel to the negative part of dp_p, then go to the right-hand-side, where the beam tail would meet the Vbb there. Thus we can observe that the bunch is kicked back from there.

In a better situation(or ideal case), the Vbb should do its own job by just restrain the bunch from becoming longer due to momentum deviation and longitudinal space charge.

Thus, when we set the Vac and Vbb, we should use a different referential signal( or with modified delays), to ensure that Vbbs are located at the equal distance from the center every turn.
Let Vbb does its job. The same thing should be applied to Vac.

May 10, 2012

Einzel lens and Momentum Modulation


What happened in DA's beam commissioning

  1. Einzel lens is adopted to chop the beam (several us out of 5ms): using Marx generator with a pulse profile.
  2. This technique has a byproduct that momentum modulation would occur to the rise and fall region of that pulse for Einzel lens.
  3. The momentum modulation in the beam head and tail has two effect: 
    1. good one: compensate somehow to the longitudinal space charge effect
    2. bad one: resulting micro-bunching inside the beam


remained issues:


  1. explain why the pulse used for Einzel lens results in momentum modulation in rise and fall region(beam head and tail)
  2. could you give a mathematical description of that process, along with related parameters, e.g. rise&fall time, dimension of einzel lens, operation voltage(for 14 kv, 17 kv ->11 kv, for 10kv, 13->8kv)
  3. what do you mean by "compensate", could you give some example?
  4. could you give a mathematical description on the effect of momentum modulation within the beam? Especially, what's the difference between motions with and without space charge? Is there still micro-bunching structure inside the beam without space charge?





May 7, 2012

Problems for the LSC with FFT


Today's task(1 simulation):

  1. compare the phase space evolution between different momentum spread without LSC
  2. find the relationship between number of bins & number of test particles versus the density profile
  3. find a better way to retrieving the density profile

(2 Master Thesis)

  1. Finishing learning LaTeX
  2. study the Material of Bac-Bdc
(3 20111116 data summary)