source: PSPA/Interface_Web/trunk/pspaWT/sources/userInterface/src/GWt_pspaApplication.cc @ 324

Last change on this file since 324 was 324, checked in by touze, 11 years ago

menu analyse graphique + histo

File size: 30.5 KB
Line 
1#include <stdio.h>
2#include <string.h>
3#include <vector>
4
5#include "GWt_pspaApplication.h"
6#include "GWt_ligneFaisceau.h"
7#include "GWt_softwarePanel.h"
8#include "GWt_globalParameters.h"
9// #include "GWt_dialog.h"
10#include "GWt_draggableImage.h"
11#include "particleBeam.h"
12#include "bareParticle.h"
13#include "nomDeLogiciel.h"
14#include "mixedTools.h"
15#include "nomdElements.h"
16#include "environmentVariables.h"
17#include "GWt_console.h"
18#include "trivaluedBool.h"
19
20#include <Wt/WGridLayout>
21#include <Wt/WVBoxLayout>
22#include <Wt/WHBoxLayout>
23#include <Wt/WImage>
24#include <Wt/WMenu>
25#include <Wt/WStackedWidget>
26#include <Wt/WBreak>
27#include <Wt/WDialog>
28#include <Wt/WStandardItemModel>
29#include <Wt/WFileUpload>
30#include <Wt/WPainter>
31#include <Wt/WPdfImage>
32#include <Wt/WRasterImage>
33#include <Wt/WScrollArea>
34#include <Wt/WLineEdit>
35#include <Wt/WRadioButton>
36
37using namespace Wt::Chart;
38
39/*
40 * The env argument contains information about the new session, and
41 * the initial request. It must be passed to the WApplication
42 * constructor so it is typically also an argument for your custom
43 * application constructor.
44 */
45
46PspaApplication::PspaApplication(const WEnvironment& env) : WApplication(env)
47{
48   
49    workingDir_ = WApplication::docRoot()+ "/"+WORKINGAREA;
50    nameOfCase_ = "pspa"; // default
51   
52    setTitle("portail PSPA");                               // application title
53    if (!wApp->environment().javaScript()) {
54        new WText("<i>This examples requires that javascript support is enabled.</i>",root());
55    }
56   
57    // register the absractElementFactory
58    abstractElementFactory_ = new GWt_abstractElementFactory();
59    abstractElementFactory_->setRFGunEnable(true);
60    abstractElementFactory_->setDriftEnable(true);
61    abstractElementFactory_->setCellEnable(true);
62    abstractElementFactory_->setBendEnable(true);
63    abstractElementFactory_->setSolenoEnable(true);
64    abstractElementFactory_->setBeamEnable(true);
65    abstractElementFactory_->setFitEnable(true);
66   
67    // include the styleSheet
68    WContainerWidget *widroot = root();
69    useStyleSheet       ("htdocs/pspa.css");
70    dtmanage_ = new dataManager(this);
71    dtmanage_->setWorkingDir(workingDir_);
72    /*
73     * The main layout is a 3x2 grid layout.
74     */
75    WGridLayout *layout = new WGridLayout();
76    //  layout->addWidget(createTitle("<a href='workingArea/parmin'> Menu (In future)</a>"), 0, 0, 1, 2);
77    //  layout->addWidget(createTitle("Menu (In future)"), 0, 0, 1, 2);
78   
79    WHBoxLayout *toolbarLayout = new WHBoxLayout();
80   
81    WPushButton* boutonSauve = new WPushButton();
82    WPushButton* boutonRestaure = new WPushButton();
83    WPushButton* boutonLoadNew = new WPushButton();
84    WPushButton* boutongraphicalAnalysis = new WPushButton();
85   
86    boutonSauve->setStyleClass("saveButton");
87    boutonRestaure->setStyleClass("restoreButton");
88    boutonLoadNew->setStyleClass("loadNewButton");
89    boutongraphicalAnalysis->setStyleClass("histoButton");
90   
91    boutonSauve->setToolTip ("sauvegarder la config");
92    boutonRestaure->setToolTip (" restaurer la config");
93    boutonLoadNew->setToolTip ("upload config");
94    boutongraphicalAnalysis->setToolTip ("analyse graphique");
95   
96    boutonSauve->setMaximumSize(38,38);
97    boutonSauve->setMinimumSize(38,38);
98    boutonRestaure->setMaximumSize(38,38);
99    boutonRestaure->setMinimumSize(38,38);
100    boutonLoadNew->setMaximumSize(38,38);
101    boutonLoadNew->setMinimumSize(38,38);
102    boutongraphicalAnalysis->setMaximumSize(38,38);
103    boutongraphicalAnalysis->setMinimumSize(38,38);
104   
105    boutonSauve->clicked().connect(this, &PspaApplication::sauver);
106    boutonRestaure->clicked().connect(this, &PspaApplication::restaurer);
107    // Upload when the button is clicked.
108    // React to a succesfull upload.
109    boutonLoadNew->clicked().connect(this, &PspaApplication::openFileSelector);
110   
111    boutongraphicalAnalysis->clicked().connect(this, &PspaApplication::dialogOnGraphics);
112   
113    toolbarLayout->addWidget(boutonSauve , 0,Wt::AlignMiddle);
114    toolbarLayout->addWidget(boutonRestaure , 0,Wt::AlignMiddle);
115    toolbarLayout->addWidget(boutonLoadNew , 0,Wt::AlignMiddle);
116    toolbarLayout->addWidget(boutongraphicalAnalysis , 0,Wt::AlignMiddle);
117    toolbarLayout->addWidget(new WText("") , 1,Wt::AlignMiddle);
118   
119    WContainerWidget * layoutContainer = new WContainerWidget();
120    layoutContainer->setLayout(toolbarLayout);
121    layoutContainer->decorationStyle().setBackgroundImage ("/htdocs/fond_toolbar.png");
122    layout->addWidget(layoutContainer, 1, 0, 1, 2);
123    layout->addWidget(createPalette(), 2, 0, 4, 1);
124   
125    createBeamLine();
126
127    WScrollArea* scroll = new  WScrollArea();
128    scroll->setWidget(beamLine_);
129    layout->addWidget(scroll, 2, 1, 1, 1);
130   
131   
132    // console_ = new WContainerWidget();
133    // console_->decorationStyle().setBackgroundColor (WColor("lightgray"));
134    // console_->setMaximumSize(600,200);
135    // layout->addWidget(console_, 3, 1);
136    // console_->setMinimumSize(300,100);
137    // console_->setOverflow(WContainerWidget::OverflowAuto);
138   
139   
140    console_ = new GWt_console();
141    console_->clear();
142    console_->decorationStyle().setBackgroundColor (WColor("lightgray"));
143    console_->setMaximumSize(600,200);
144    console_->setMinimumSize(300,100);
145    console_->setOverflow(WContainerWidget::OverflowAuto);
146    layout->addWidget(console_, 3, 2);
147   
148    //-----------
149    // A supprimer et a mettre en fenetre
150    globalParam_ = createGlobalParamWidget();
151    //  leDessin_ = new WContainerWidget();
152    //  leDessin_ = createDrawingWidget();
153    graphicsDialog_ = new GWt_dialog("graphical analysis",createDrawingWidget(),false);
154    graphicsDialog_->setMinimumSize(400,400);
155    graphicsDialog_->setClosable(true);
156   
157    executeWidget_ = new GWt_softwarePanel(dtmanage_,this);
158   
159    layout->addWidget( globalParam_, 3, 1);
160    //  layout->addWidget( leDessin_, 3, 2);
161    layout->addWidget( executeWidget_ , 4, 1);
162    //-----------
163     
164    layout->setColumnResizable(1);
165    layout->setRowResizable(2);
166    /*
167     * Let row 2 and column 1 take the excess space.
168     */
169    layout->setRowStretch(2, 1);
170    layout->setColumnStretch(1, 1);
171   
172    widroot->setLayout(layout);
173}
174
175WWidget* PspaApplication::createPalette()
176{
177  WContainerWidget* palette = new WContainerWidget();
178  vector <GWt_abstractElement*> elems = abstractElementFactory_->getAllElements();
179  for (unsigned a = 0; a < elems.size(); a++) {
180    elems[a]->createDragImage(palette);
181    new WBreak(palette);
182  }
183
184  return palette; 
185}
186
187void PspaApplication::createDragImage(const char *url,const char *smallurl,const char *mimeType,WContainerWidget *p,WString())
188{
189  GWt_draggableImage *result = new GWt_draggableImage(url,p);
190 
191  /*
192   * Set the image to be draggable, showing the other image (dragImage)
193   * to be used as the widget that is visually dragged.
194   */
195  result->setDraggable(mimeType,new WImage(smallurl,p),true);
196}
197
198void PspaApplication::createBeamLine()
199{
200  beamLine_ = new GWt_LigneFaisceau(this);
201  beamLine_->setMinimumSize(300,100);
202}
203
204WWidget* PspaApplication::createGlobalParamWidget()
205{
206    WContainerWidget* globalParam = new GWt_globalParameters(this);
207    globalParam->setMaximumSize(600,150);
208    globalParam->setMinimumSize(600,150);
209    return globalParam;
210}
211
212
213void PspaApplication::dialogOnGraphics()
214{
215  graphicsDialog_->show();
216}
217
218WContainerWidget* PspaApplication::createDrawingWidget()
219{
220  WGridLayout *glayout= new WGridLayout();
221  WContainerWidget* dessin = new WContainerWidget();
222  dessin->setLayout(glayout);
223
224  group_ = new Wt::WButtonGroup(this);
225 
226  /////////////////////////////////////////////////////////////////////
227       
228  choixEnveloppeDessin_ = new WComboBox();
229  choixEnveloppeDessin_->addItem("x");
230  // choixEnveloppeDessin_->addItem("y");
231  Wt::WRadioButton *button1= new WRadioButton(" enveloppe");
232  group_->addButton(button1,1);
233  glayout->addWidget(button1,0,1);
234  glayout->addWidget(choixEnveloppeDessin_,0,2);
235  /////////////////////////////////////////////////////////////////////
236
237  choixElementDessin_ = new WComboBox();
238  choixTypeDessinFaisceau_ = new WComboBox();
239  choixTypeDessinFaisceau_->addItem("courant_snyder");
240  choixTypeDessinFaisceau_->addItem("macroparticles");
241  Wt::WRadioButton *button2= new WRadioButton(" phase space after element");
242  group_->addButton(button2,2);
243  glayout->addWidget(button2,1,1);
244  glayout->addWidget(choixElementDessin_,1,2);
245  glayout->addWidget(choixTypeDessinFaisceau_,1,3);
246  /////////////////////////////////////////////////////////////////////
247
248  choixHistoDessin_ = new WComboBox();
249  Wt::WRadioButton *button3= new WRadioButton(" histogram after element");
250  group_->addButton(button3,3);
251  glayout->addWidget(button3,2,1);
252  glayout->addWidget(choixHistoDessin_,2,2);
253  /////////////////////////////////////////////////////////////////////
254 
255  WPushButton *close= new WPushButton("close"); 
256  glayout->addWidget(close,3,1);
257  close->clicked().connect(this,&PspaApplication::closeGraphicDialog);
258 
259  WPushButton *draw= new WPushButton("draw"); 
260  glayout->addWidget(draw,3,2,2,1);
261  draw->clicked().connect(this,&PspaApplication::dessiner);
262  /////////////////////////////////////////////////////////////////////
263
264  toto_ = new WContainerWidget();
265  dessin->addWidget(toto_);
266  return dessin;
267}
268
269void PspaApplication::closeGraphicDialog()
270{
271  cout << " close graphicsDialog_" << endl;
272  graphicsDialog_->done(WDialog::Rejected);
273}
274
275void PspaApplication::dessiner()
276{
277  int k= group_->checkedId();
278  cout << "dessiner k= " << k << endl;
279
280  switch(k) {
281  case  1: 
282    dessinerEnveloppe();
283    break;
284  case 2:
285    dessinerPhaseSpace();
286    break;
287  case 3:
288    dessinerHistogramme();
289    break;
290  default:
291    GWt_dialog graphicalWarning("graphical analysis","select a button",GWt_dialog::Warning,false,true);
292    graphicalWarning.exec();
293    break;
294  }
295}
296
297void PspaApplication::sauver()
298{
299  cout << " on sauve " << endl;
300  console_->addConsoleMessage("sauvegarde");
301 
302  dialogSave_ = new WDialog("save");
303  new WText("name of case : ",dialogSave_->contents());
304  saveNameEdit_ = new WLineEdit(nameOfCase_.c_str(), dialogSave_->contents());
305  WPushButton *annule = new WPushButton("cancel",dialogSave_->contents());
306  WPushButton *submit = new WPushButton("OK",dialogSave_->contents());
307  annule->clicked().connect(dialogSave_, &Wt::WDialog::reject);
308  submit->clicked().connect(dialogSave_, &Wt::WDialog::accept);
309  dialogSave_->finished().connect(this, &PspaApplication::dialogSaveDone);
310  dialogSave_->show();
311}
312
313void PspaApplication::dialogSaveDone(WDialog::DialogCode code)
314{
315 
316  if ( code != Wt::WDialog::Accepted ) { console_->addConsoleMessage(" pas de sauvegarde"); return;}
317  else { console_->addConsoleMessage("sauvegarde sur repertoire : " + workingDir_);}
318  nameOfCase_ = saveNameEdit_->text().toUTF8();
319  cout << " PspaApplication::dialogSaveDone() nameOfCase_= " << nameOfCase_ << endl;
320  delete dialogSave_;
321  dialogSave_ = NULL;
322  GWt_globalParameters* bibi = static_cast<GWt_globalParameters*>(globalParam_);
323  bibi->updateGlobals();
324  //  dtmanage_->saveConfiguration(nameOfCase_);
325  dtmanage_->saveConfiguration( nameOfCase_);
326}
327
328void PspaApplication::restaurer()
329{
330    console_->addConsoleMessage(string("on va recharger..."));
331    dialogOpen_ = new WDialog("open");
332    new WText("name of case : ",dialogOpen_->contents());
333    openNameEdit_ = new WLineEdit(nameOfCase_.c_str(), dialogOpen_->contents());
334    WPushButton *annule = new WPushButton("cancel",dialogOpen_->contents());
335    WPushButton *submit = new WPushButton("OK",dialogOpen_->contents());
336    annule->clicked().connect(dialogOpen_, &Wt::WDialog::reject);
337    submit->clicked().connect(dialogOpen_, &Wt::WDialog::accept);
338    dialogOpen_->finished().connect(this, &PspaApplication::dialogOpenDone);
339    dialogOpen_->show();
340}
341
342void PspaApplication::dialogOpenDone(WDialog::DialogCode code)
343{   
344  if (code != Wt::WDialog::Accepted) { 
345    console_->addConsoleMessage(" pas de restauration"); 
346    return;
347  } else { 
348    console_->addConsoleMessage("restauration depuis le repertoire " + workingDir_ );
349  }
350   
351  nameOfCase_ = openNameEdit_->text().toUTF8();
352  cout << " PspaApplication::dialogOpenDone() nameOfCase_= " << nameOfCase_ << endl;
353  delete dialogOpen_;
354  dialogSave_ = NULL;
355 
356  bool test = dtmanage_->restoreElements(nameOfCase_);
357  if ( !test ) {
358    GWt_dialog restoreWarning(" element restoring", "failure in restoring elements !", GWt_dialog::Error, false,true);
359    restoreWarning.exec();
360  }
361 
362  GWt_globalParameters* bibi = static_cast<GWt_globalParameters*>(globalParam_);
363  bibi->renew();
364 
365  console_->addConsoleMessage(string("...terminee"));
366}
367
368void PspaApplication::openFileSelector()
369{
370   
371  WContainerWidget *result = new WContainerWidget();
372  WVBoxLayout* myLayout = new WVBoxLayout();
373   
374  uploadFileSelectorWidget_ = new WFileUpload();
375   
376  uploadFileSelectorWidget_->setFileTextSize(40);
377   
378  myLayout->addWidget(new WText("Select the configuration file for pspa : "));
379  myLayout->addWidget(uploadFileSelectorWidget_);
380   
381  result->setLayout (myLayout);
382   
383  // Upload automatically when the user entered a file.
384  uploadFileSelectorWidget_->changed().connect(uploadFileSelectorWidget_, &WFileUpload::upload);
385 
386  // React to a succesfull upload.
387  uploadFileSelectorWidget_->uploaded().connect(this, &PspaApplication::chargerConfig);
388 
389  // React to a fileupload problem.
390  uploadFileSelectorWidget_->fileTooLarge().connect(this, &PspaApplication::fileTooLarge);
391 
392 
393  GWt_dialog* fileSelectorDialog = new GWt_dialog("Load a file",result,false);
394 
395  fileSelectorDialog->exec();
396}
397
398void PspaApplication::chargerConfig()
399{
400    GWt_dialog*  message= new GWt_dialog("File successfully upload","The file has been correctly upload to" + uploadFileSelectorWidget_->spoolFileName(),GWt_dialog::Warning,false,true);
401   
402    string nomDuFichier = (uploadFileSelectorWidget_->clientFileName()).toUTF8();
403    cout << " fichier client : " << nomDuFichier << endl;
404    bool test = removeExtensionFromConfigName(nomDuFichier);
405    cout << " fichier client sans extension : " << nomDuFichier << endl;
406   
407    if ( test )
408    {
409        nameOfCase_ = nomDuFichier;
410        console_->addConsoleMessage(string("restauration..."));
411       
412        if ( !dtmanage_->restoreElements(uploadFileSelectorWidget_->spoolFileName()) ) {
413            GWt_dialog restoreWarning(" element restoring", "failure in restoring elements !", GWt_dialog::Error, false,true);
414            restoreWarning.exec();
415        }
416       
417        GWt_globalParameters* bibi = static_cast<GWt_globalParameters*>(globalParam_);
418        bibi->renew();
419               
420        console_->addConsoleMessage(string("...terminee"));
421        message->show();
422    }
423}
424
425
426void PspaApplication::fileTooLarge()
427{
428    std::stringstream stream;
429    stream << maximumRequestSize ();
430    std::string maxRequestSize(stream.str());
431   
432    std::string message = "This file is too large, please select a one\n";
433    message += "Maximum file size is "+ maxRequestSize;
434    message += " bytes\n";
435   
436    GWt_dialog*  messageBox= new GWt_dialog("Error during upload file" ,message ,GWt_dialog::Error,false,true);
437   
438    messageBox->show();
439}
440
441void PspaApplication::faireDessin()
442{
443  choixElementDessin_->clear();
444  choixHistoDessin_->clear();
445  int nombre = dtmanage_->getBeamLineSize();
446  cout << " PspaApplication::faireDessin() nb elements : " << nombre << endl;
447  for(int i = 1; i <= nombre; i++) {
448    choixElementDessin_->addItem(dtmanage_->getLabelFromElementNumero(i));
449    choixHistoDessin_->addItem(dtmanage_->getLabelFromElementNumero(i));
450  } 
451}
452
453void PspaApplication::dessinerPhaseSpace()
454{   
455  toto_->clear();
456   
457  int typeFaisceau = choixTypeDessinFaisceau_->currentIndex(); 
458  int index = choixElementDessin_->currentIndex();
459  particleBeam* beam = dtmanage_->getDiagnosticBeam(index);
460   
461  if ( beam == NULL ) {
462    GWt_dialog warningBeamState(" graphical analysis", "the beam does not exist at the end of this element !", GWt_dialog::Error, false,true);
463    warningBeamState.exec();
464    return;
465  }
466     
467  if ( typeFaisceau == 0 )
468    {
469      if ( !beam->momentRepresentationOk() ) beam->buildMomentRepresentation();
470      faireDessinTransport(toto_, beam);
471    }
472  else if ( typeFaisceau == 1 )
473    {
474      if ( beam->particleRepresentationOk() ) faireDessinParmela(toto_, beam);
475      else {
476        GWt_dialog warningBeamState(" graphical analysis", "the beam state does not allow providing a drawing with macroparticles !", GWt_dialog::Error, false,true);
477        warningBeamState.exec();
478      }
479    }
480  else {
481    GWt_dialog warningTypeDrawing(" graphical analysis", "type of  drawing not programmed !", GWt_dialog::Error, false,true);
482    warningTypeDrawing.exec();
483  }
484}
485
486void PspaApplication::dessinerEnveloppe()
487{
488  toto_->clear();
489 
490  int typeEnveloppe = choixEnveloppeDessin_->currentIndex();
491  if ( typeEnveloppe == 0 )
492    {
493      faireDessinEnveloppe(toto_, "x");
494    }
495  else {
496    GWt_dialog warningTypeEnveloppe(" graphical analysis", "type of enveloppe drawing not programmed !", GWt_dialog::Error, false,true);
497    warningTypeEnveloppe.exec();
498  }
499}
500
501void PspaApplication::faireDessinEnveloppe(WContainerWidget* toto, string type)
502{
503   
504  GWt_dialog* envDialog = new GWt_dialog("enveloppe",toto,false);
505  envDialog->setMinimumSize(400,400);
506  envDialog->setClosable(true);
507  envDialog->show();
508     
509  //       new WText(nameOfCase_ + " : enveloppe", toto);
510  unsigned nbel = dtmanage_->getBeamLineSize();
511  vector<double> xcor;
512  vector<double> ycor;
513  dtmanage_->donneesRmsEnveloppe(type,1, nbel, xcor,ycor);
514  scatterPlot1D(envDialog->contents(),xcor,ycor); 
515}
516
517void PspaApplication::faireDessinParmela(WContainerWidget* toto, particleBeam* beam)
518{
519   
520    GWt_dialog* pointsDialog = new GWt_dialog("space phase",toto,false);
521    pointsDialog->setMinimumSize(400,400);
522    pointsDialog->setClosable(true);
523    // pointsDialog->show();
524   
525   
526   
527    vector<bareParticle>& partic = beam->getParticleVector();
528    new WText(nameOfCase_ + " : espace de phase x,x' "+ " nb partic. "+ mixedTools::intToString(partic.size()), pointsDialog->contents());
529    WStandardItemModel *model = new WStandardItemModel(partic.size(), 3, pointsDialog->contents());
530    //    model->setHeaderData(0, WString("X"));
531    //   model->setHeaderData(1, WString("Y = sin(X)"));
532   
533   
534    for (unsigned i = 0; i < partic.size(); ++i) {
535        double x= partic.at(i).getPosition().getComponent(0);
536        double begamz = partic.at(i).getBetaGamma().getComponent(2);
537        double xp;
538        if ( begamz != 0.0) {
539          xp = partic.at(i).getBetaGamma().getComponent(0)/begamz;
540        } else {
541          xp = 0.0;
542        }
543        //    cout << "x = " << x << " xp= " << xp << endl;
544        model->setData(i, 0, x);
545        model->setData(i, 1,1.e3*xp);
546        model->setData(i, 2,2.e3*xp);
547    }
548   
549    WCartesianChart *chart = new WCartesianChart(pointsDialog->contents());
550    chart->setModel(model);        // set the model
551    chart->setXSeriesColumn(0);    // set the column that holds the X data
552    chart->setLegendEnabled(true); // enable the legend
553   
554    chart->setType(ScatterPlot);   // set type to ScatterPlot
555   
556    // Typically, for mathematical functions, you want the axes to cross
557    // at the 0 mark:
558    chart->axis(XAxis).setLocation(ZeroValue);
559    chart->axis(YAxis).setLocation(ZeroValue);
560   
561    // Provide space for the X and Y axis and title.
562    chart->setPlotAreaPadding(80, Left);
563    chart->setPlotAreaPadding(40, Top | Bottom);
564    // Add the curves
565    WDataSeries s(1, PointSeries, Y1Axis);
566    //  s.setShadow(WShadow(3, 3, WColor(0, 0, 0, 127), 3));
567    //    s.setMarker(SquareMarker);
568    //  s.setMarkerSize(600.);
569    //  cout << "le marker est : " << s.marker() << endl;
570    chart->addSeries(s);
571   
572    chart->resize(400, 400); // WPaintedWidget must be given explicit size
573   
574   
575#ifdef HAS_IMAGEMAGIC
576    Wt::WRasterImage pngImage("png", 600, 600);
577    Wt::WPainter p(&pngImage);
578    chart->paint(p);
579    std::string name;
580    name = workingDir_ + "/chart-"+sessionId ()+".png";
581    std::ofstream f(name.c_str(), std::ios::out |std::ios::trunc | std::ios::binary);
582    pngImage.write(f);
583    new WText("<a href='workingArea/chart-"+sessionId ()+".png' target='_blank'>Afficher l'image</a>",toto);
584#endif
585   
586    pointsDialog->show();
587   
588    //  chart->setMargin(10, Top | Bottom);            // add margin vertically
589    //  chart->setMargin(WLength::Auto, Left | Right); // center horizontally
590}
591
592
593// void PspaApplication::addElemToGlobals()
594// {
595//   static_cast<GWt_globalParameters*>(globalParam_)->addElem();
596// }
597
598void PspaApplication::faireDessinTransport(WContainerWidget* toto, particleBeam* beam)
599{
600    //  WContainerWidget* toto = static_cast<WContainerWidget*>(leDessin_);
601    //  toto->clear();
602   
603    //  new WText(nameOfCase_ + " : espace de phase x,x' "+ " nb partic. "+ mixedTools::intToString(partic.size()), toto);
604   
605    GWt_dialog* ellipseDialog = new GWt_dialog("ellipse",toto,false);
606    ellipseDialog->setMinimumSize(400,400);
607    ellipseDialog->setClosable(true);
608    ellipseDialog->show();
609   
610   
611    new WText(nameOfCase_ + " : emittance x,x' " + mixedTools::doubleToString(beam->getUnnormalizedEmittanceX()) + " pi.mm.mrad" , ellipseDialog->contents());
612    new WBreak(ellipseDialog->contents());
613    new WText(" xmax = " + mixedTools::doubleToString(beam->getSigmaTransportij(1,1)) + " cm ", ellipseDialog->contents());
614    new WBreak(ellipseDialog->contents());
615    new WText(" x' max = " + mixedTools::doubleToString(beam->getSigmaTransportij(2,2)) + " mrad ", ellipseDialog->contents());
616    new WBreak(ellipseDialog->contents());
617    new WText(" corr. 12 = " + mixedTools::doubleToString(beam->getSigmaTransportij(2,1))  + " sqrt(cm.rad) ", ellipseDialog->contents());
618   
619    vector<double> xcor;
620    vector<double> ycor;
621    //  dtmanage_->getCurrentBeam()->donneesDessinEllipseXxp(xcor,ycor);
622    beam->donneesDessinEllipseXxp(xcor,ycor);
623    scatterPlot1D(ellipseDialog->contents(),xcor,ycor);
624   
625}
626
627// void PspaApplication::scatterPlot1D(WContainerWidget* toto, vector<double>& xcor, vector<double>& ycor)
628// {
629//   int nbpts = xcor.size();
630//   cout << " PspaApplication::scatterPlot1D nbpts = " << nbpts << endl;
631//   WStandardItemModel *model = new WStandardItemModel(nbpts, 2, toto);
632//   for (int i = 0; i < nbpts; ++i) {
633//     model->setData(i, 0, xcor.at(i));
634//     model->setData(i, 1, ycor.at(i));
635//     //    cout << " PspaApplication::scatterPlot1D el= " << i+1 << " x= " << xcor.at(i) << " y= " << ycor.at(i) << endl;
636//   }
637
638//   WCartesianChart *chart = new WCartesianChart(toto);
639
640//   chart->initLayout();
641
642//   chart->setModel(model);        // set the model
643//   chart->setXSeriesColumn(0);    // set the column that holds the X data
644//   chart->setLegendEnabled(true); // enable the legend
645
646//   chart->setType(ScatterPlot);   // set type to ScatterPlot
647
648//   // Typically, for mathematical functions, you want the axes to cross
649//   // at the 0 mark:
650//    chart->axis(XAxis).setLocation(ZeroValue);
651//    chart->axis(YAxis).setLocation(ZeroValue);
652
653//   // Provide space for the X and Y axis and title.
654// //   chart->setPlotAreaPadding(80, Left);
655// //   chart->setPlotAreaPadding(40, Top | Bottom);
656//   // Add the curves
657//   WDataSeries s(1, CurveSeries, Y1Axis);
658//   chart->addSeries(s);
659
660//   // chart->setBackground (WBrush(WColor("blue")));
661//   chart->resize(300, 300); // WPaintedWidget must be given explicit size
662
663// #ifdef HAS_IMAGEMAGIC
664//  Wt::WRasterImage pngImage("png", 600, 600);
665//  Wt::WPainter p(&pngImage);
666
667//  chart->paint(p);
668//  std::string name;
669//  name = workingDir_ + "/chart-"+sessionId ()+".png";
670//  std::ofstream f(name.c_str(), std::ios::out |std::ios::trunc | std::ios::binary);
671//  pngImage.write(f);
672
673//  new WText("<a href='workingArea/chart-"+sessionId ()+".png' target='_blank'>Afficher l'image</a>",toto);
674
675//  /*
676//  Wt::WPdfImage pdfImage("30cm", "30cm");
677//  Wt::WPainter p1(&pdfImage);
678//  chart->paint(p1);
679//  std::ofstream f1("chart.pdf", std::ios::out | std::ios::binary);
680//  pdfImage.write(f1);
681//  */
682// #endif
683// }
684
685
686void PspaApplication::scatterPlot1D(WContainerWidget* toto, vector<double>& xcor, vector<double>& ycor)
687{
688    int nbpts = xcor.size();
689    cout << " PspaApplication::scatterPlot1D nbpts = " << nbpts << endl;
690    WStandardItemModel *model = new WStandardItemModel(nbpts, 2, toto);
691    for (int i = 0; i < nbpts; ++i) {
692        model->setData(i, 0, xcor.at(i));
693        model->setData(i, 1, ycor.at(i));
694        //    cout << " PspaApplication::scatterPlot1D el= " << i+1 << " x= " << xcor.at(i) << " y= " << ycor.at(i) << endl;
695    }
696   
697    WCartesianChart *chart = new WCartesianChart(toto);
698    chart->setTitle("titre");
699   
700    //  chart->initLayout();
701   
702    chart->setModel(model);        // set the model
703    chart->setXSeriesColumn(0);    // set the column that holds the X data
704    chart->setLegendEnabled(true); // enable the legend
705   
706    chart->setType(ScatterPlot);   // set type to ScatterPlot
707   
708    // Typically, for mathematical functions, you want the axes to cross
709    // at the 0 mark:
710    chart->axis(XAxis).setLocation(ZeroValue);
711    chart->axis(YAxis).setLocation(ZeroValue);
712   
713    // Provide space for the X and Y axis and title.
714    //   chart->setPlotAreaPadding(80, Left);
715    //   chart->setPlotAreaPadding(40, Top | Bottom);
716    // Add the curves
717    WDataSeries s(1, LineSeries, Y1Axis);
718    chart->addSeries(s);
719   
720    // chart->setBackground (WBrush(WColor("blue")));
721    chart->resize(500, 300); // WPaintedWidget must be given explicit size
722   
723#ifdef HAS_IMAGEMAGIC
724    Wt::WRasterImage pngImage("png", 600, 600);
725    Wt::WPainter p(&pngImage);
726   
727    chart->paint(p);
728    std::string name;
729    name = workingDir_ + "/chart-"+sessionId ()+".png";
730    std::ofstream f(name.c_str(), std::ios::out |std::ios::trunc | std::ios::binary);
731    pngImage.write(f);
732   
733    new WText("<a href='workingArea/chart-"+sessionId ()+".png' target='_blank'>Afficher l'image</a>",toto);
734   
735    /*
736     Wt::WPdfImage pdfImage("30cm", "30cm");
737     Wt::WPainter p1(&pdfImage);
738     chart->paint(p1);
739     std::ofstream f1("chart.pdf", std::ios::out | std::ios::binary);
740     pdfImage.write(f1);
741     */
742#endif
743}
744
745
746
747WText* PspaApplication::createTitle(const WString& title)
748{
749  WText *result = new WText(title);
750  result->setInline(false);
751  result->setStyleClass("title");
752  result->setMinimumSize(30,30);
753 
754  return result;
755}
756
757// void PspaApplication::addConsoleMessage(WString msg) {
758//   WText *w = new WText(console_);
759//   w->setTextFormat(PlainText);
760//   w->setText(msg);
761//   w->setInline(false);
762
763//   /*
764//    * Little javascript trick to make sure we scroll along with new content
765//    */
766//   WApplication *app = WApplication::instance();
767//   app->doJavaScript(console_->jsRef() + ".scrollTop += "
768//                     + console_->jsRef() + ".scrollHeight;");
769
770// }
771
772bool PspaApplication::removeExtensionFromConfigName(string& config)
773{
774    //  string configName;
775    string extension(".save");
776    bool test = true;
777    string::size_type nn = config.rfind('.');
778    if ( nn == string::npos )
779    {
780        // pas de point
781        test = false;
782    }
783    string fin = config.substr(nn);
784    if ( fin != extension )
785    {
786        // l'extension n'est pas la bonne
787        test = false;
788    }
789    if ( test )
790    {
791        string::size_type count = config.length() - extension.length();
792        config = config.substr(0, count);
793    }
794    else
795    {
796        GWt_dialog checkConfigNameDialog(" checking config file name", " the file must have the extension " + extension, GWt_dialog::Error,true,true);
797        checkConfigNameDialog.exec();
798    }
799    return test;
800}
801
802void PspaApplication::dessinerHistogramme()
803{
804  // pour mon test : histo en energie
805  toto_->clear();
806   
807  GWt_dialog* pourVoir= new GWt_dialog("histogramme",toto_,false);
808  pourVoir->setMinimumSize(400,400);
809  pourVoir->setClosable(true);
810  pourVoir->show();
811 
812  int index = choixHistoDessin_->currentIndex();   
813  particleBeam* beam = dtmanage_->getDiagnosticBeam(index);
814  if (beam == NULL) {
815    GWt_dialog warningBeamState("histogram","the beam does not exist at the end of this element !", GWt_dialog::Error, false,true);
816    warningBeamState.exec();
817    return;
818  }
819 
820  if (!beam->particleRepresentationOk()) {
821    GWt_dialog warningBeamState("histogram", "the beam state does not allow providing a drawing with macroparticles !", GWt_dialog::Error, false,true);
822    warningBeamState.exec();
823    return;
824  }
825
826  vector<double> xcor;
827  vector<int> hist;
828  int cnts;
829  double out[3]= {0.0};
830  beam->histogramme(xcor,hist,cnts,out);
831 
832  cout<<"xcor.size()= "<<xcor.size()<<", hist.size()= "<<hist.size()<<endl;
833  //////////////////////////////////////////////////////////////////////////////////
834   
835  WContainerWidget *w = toto_;
836  int nbpts= xcor.size()+cnts+1;
837  WStandardItemModel *model = new WStandardItemModel(nbpts,2,w);
838  model->setHeaderData(1, WString("energie"));
839 
840  int j= 0;
841  if(hist[0] > 0) {
842    model->setData(j,0,xcor[0]);
843    model->setData(j,1,hist[0]);
844    j++;
845  }
846  model->setData(j,0,xcor[0]);
847  model->setData(j,1,hist[0]);
848  j++;
849  for (int i = 1; i < nbpts; ++i) {
850    if(hist[i] == 0) {
851      if(hist[i-1] > 0) {
852        model->setData(j,0,xcor[i]);
853        model->setData(j,1,hist[i-1]);
854        j++;
855      }
856      model->setData(j,0,xcor[i]);
857      model->setData(j,1,hist[i]);
858      j++;
859    }
860    if(hist[i] > 0) {
861      model->setData(j,0,xcor[i]);
862      model->setData(j,1,hist[i-1]);
863      j++;
864      model->setData(j,0,xcor[i]);
865      model->setData(j,1,hist[i]);
866      j++;
867    }
868  }
869 
870  // legendes
871  new WText(" entries : "+ mixedTools::intToString((int)out[0]),w);
872  new WBreak(w);
873  new WText(" mean : "+ mixedTools::doubleToString(out[1])+" MeV",w);
874  new WBreak(w);
875  new WText(" rms : "+ mixedTools::doubleToString(out[2])+" KeV",w);
876 
877  WCartesianChart *chart = new WCartesianChart(w);
878  chart->setTitle("Histogram of particle energies");
879  chart->setModel(model);        // set the model
880  chart->setXSeriesColumn(0);    // set the column that holds the categories
881  chart->setLegendEnabled(false); // enable the legend
882   
883  // Provide space for the X and Y axis and title.
884  chart->setPlotAreaPadding(200, Right);
885  chart->setPlotAreaPadding(80, Left);
886  chart->setPlotAreaPadding(40, Top | Bottom);
887   
888  chart->setType(ScatterPlot);
889   
890  WAxis& axis = chart->axis(XAxis);
891  axis.setLabelFormat("%.3f");
892  axis.setGridLinesEnabled(true);
893  axis.setTitle(WString("legende x"));
894
895  chart->axis(Y1Axis).setGridLinesEnabled(true);
896  chart->axis(Y1Axis).setTitle(WString("legende y"));
897   
898  WDataSeries s(1, LineSeries);
899  s.setFillRange(ZeroValueFill);
900  chart->addSeries(s);
901   
902  chart->resize(800, 400);
903  chart->setMargin(10, Top | Bottom);
904  chart->setMargin(WLength::Auto, Left | Right);
905   
906  LegendLocation location = LegendOutside;
907  Side side = Right;
908  AlignmentFlag alignment = AlignMiddle;
909  chart->setLegendLocation(location, side, alignment);
910  chart->setLegendStyle(chart->legendFont(), WPen(black), WBrush(WColor(0xFF, 0xFA, 0xE5)));
911}
Note: See TracBrowser for help on using the repository browser.