source: xssim/branches/tpiontek/src/simulator/stats/implementation/GSSimStatistics.java @ 269

Revision 269, 48.6 KB checked in by piontek, 13 years ago (diff)
  • Property svn:mime-type set to text/plain
Line 
1package simulator.stats.implementation;
2
3import gridsim.gssim.GssimConstants;
4import gridsim.gssim.ResourceHistoryItem;
5import gssim.schedframe.scheduling.AbstractExecutable;
6import gssim.schedframe.scheduling.ExecTaskInterface;
7
8import java.awt.Color;
9import java.awt.Paint;
10import java.io.File;
11import java.io.FileOutputStream;
12import java.io.IOException;
13import java.io.PrintStream;
14import java.text.NumberFormat;
15import java.util.ArrayList;
16import java.util.Calendar;
17import java.util.Collections;
18import java.util.Comparator;
19import java.util.Date;
20import java.util.HashMap;
21import java.util.List;
22import java.util.Map;
23import java.util.SortedMap;
24import java.util.TreeMap;
25
26import org.apache.commons.logging.Log;
27import org.apache.commons.logging.LogFactory;
28import org.jfree.chart.ChartFactory;
29import org.jfree.chart.ChartRenderingInfo;
30import org.jfree.chart.ChartUtilities;
31import org.jfree.chart.JFreeChart;
32import org.jfree.chart.axis.AxisLocation;
33import org.jfree.chart.axis.DateAxis;
34import org.jfree.chart.axis.NumberAxis;
35import org.jfree.chart.encoders.ImageFormat;
36import org.jfree.chart.labels.CategoryItemLabelGenerator;
37import org.jfree.chart.labels.ItemLabelAnchor;
38import org.jfree.chart.labels.ItemLabelPosition;
39import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
40import org.jfree.chart.plot.CategoryPlot;
41import org.jfree.chart.plot.CombinedDomainXYPlot;
42import org.jfree.chart.plot.PlotOrientation;
43import org.jfree.chart.plot.XYPlot;
44import org.jfree.chart.renderer.category.CategoryItemRenderer;
45import org.jfree.chart.renderer.category.GanttRenderer;
46import org.jfree.chart.renderer.xy.XYStepAreaRenderer;
47import org.jfree.chart.title.TextTitle;
48import org.jfree.chart.title.Title;
49import org.jfree.data.gantt.TaskSeries;
50import org.jfree.data.gantt.TaskSeriesCollection;
51import org.jfree.data.time.FixedMillisecond;
52import org.jfree.data.xy.XYDataset;
53import org.jfree.data.xy.XYSeries;
54import org.jfree.data.xy.XYSeriesCollection;
55import org.jfree.ui.TextAnchor;
56import org.joda.time.DateTime;
57import org.joda.time.DateTimeUtilsExt;
58
59import schedframe.resources.profile.PowerUsage;
60import schedframe.resources.units.ResourceUnit;
61import schedframe.scheduling.Job;
62import schedframe.scheduling.JobInterface;
63import schedframe.scheduling.utils.ResourceParameterName;
64import simulator.ConfigurationOptions;
65import simulator.GenericUser;
66import simulator.GridSchedulingSimulator;
67import simulator.stats.GSSAccumulator;
68import simulator.stats.SimulationStatistics;
69import simulator.stats.implementation.out.AbstractStringSerializer;
70import simulator.stats.implementation.out.FormatedStringSerializer;
71import simulator.stats.implementation.out.StringSerializer;
72import test.rewolucja.energy.extension.EnergyExtension;
73import test.rewolucja.extensions.Extension;
74import test.rewolucja.extensions.ExtensionList;
75import test.rewolucja.extensions.ExtensionType;
76import test.rewolucja.resources.ProcessingElements;
77import test.rewolucja.resources.ResourceType;
78import test.rewolucja.resources.exception.ResourceException;
79import test.rewolucja.resources.physical.base.ComputingResource;
80import test.rewolucja.resources.physical.implementation.ComputingNode;
81import test.rewolucja.resources.physical.implementation.Processor;
82import test.rewolucja.resources.utils.ResourceController;
83import test.rewolucja.scheduling.JobRegistry;
84import csiro.mit.utils.jfreechart.timetablechart.TimetableChartFactory;
85import csiro.mit.utils.jfreechart.timetablechart.data.Timetable;
86import csiro.mit.utils.jfreechart.timetablechart.data.TimetableEventGroup;
87import csiro.mit.utils.jfreechart.timetablechart.data.TimetableEventSource;
88import csiro.mit.utils.jfreechart.timetablechart.renderer.TimetableRenderer;
89
90public class GSSimStatistics implements SimulationStatistics {
91
92        private Log log = LogFactory.getLog(GSSimStatistics.class);
93
94        protected static float ALPHA = 0.5f;
95        protected static int GANTT_WIDTH = 1200;
96
97        //protected static final int BITS = 8;
98        //protected static final int MILLI_SEC = 1000;
99
100        protected static final String RAW_TASKS_STATISTICS_OUTPUT_FILE_NAME = "Tasks.txt";
101        protected static final String CATEGORY_TASKS_STATISTICS_OUTPUT_FILE_NAME = "TasksCategory.txt";
102        protected static final String JOBS_STATISTICS_OUTPUT_FILE_NAME = "Jobs.txt";
103
104        protected static final String SIMULATION_STATISTICS_OUTPUT_FILE_NAME = "Simulation.txt";
105        protected static final String ENERGYUSAGE_STATISTICS_OUTPUT_FILE_NAME = "Energy.txt";
106        protected static final String RESOURCEUSAGE_STATISTICS_OUTPUT_FILE_NAME = "ResourceUtilization.txt";
107
108        protected static final String DIAGRAMS_FILE_NAME_PREFIX = "Chart_";
109        protected static final String STATS_FILE_NAME_PREFIX = "Stats_";
110
111        protected static final String TASK_SEPARATOR = ";";
112        protected static final String JOB_SEPARATOR = ";";
113
114        protected String outputFolderName;
115
116        protected String simulationIdentifier;
117        protected ConfigurationOptions configuration;
118
119
120
121
122        protected GSSAccumulatorsStats accStats;
123       
124        private GenericUser users;
125        protected ResourceController resourceController;
126        protected boolean generateDiagrams = true;
127        protected AbstractStringSerializer serializer;
128        protected long startSimulationTime;
129        protected long endSimulationTime;
130       
131       
132        //RESOURCES
133        protected Timetable ganttDiagramPeTimetable;
134        protected Map<ResourceType, List<XYDataset>> resourceEnergyDiagrams;
135        protected Map<ResourceType, List<XYDataset>> resourceLoadDiagrams;
136        protected Map<String,List<ResStat>> basicResStats;
137        protected HashMap<String, Double> basicResLoad;
138       
139        protected Map<String, TimetableEventSource> peGanttMap;
140        protected Map<String, TimetableEventGroup> taskGanttMap;
141       
142       
143        //TASKS
144        protected int numOfdelayedTasks = 0;
145        protected int numOfNotExecutedTasks = 0;
146        protected double maxCj = 0;
147
148        protected boolean allTasksFinished;
149        protected TaskSeriesCollection ganttDiagramTaskSeriesCollection;
150        protected TaskSeriesCollection ganttDiagramWaitingTimeSeriesCollection;
151        protected HashMap<String, List<String>> task_processorsMap;
152
153       
154
155
156        JobRegistry jr;
157
158       
159        public GSSimStatistics(String simulationIdentifier, ConfigurationOptions co, GenericUser users,
160                        String outputFolderName, ResourceController resourceController) {
161                this.simulationIdentifier = simulationIdentifier;
162                this.configuration = co;
163                this.users = users;
164
165                this.outputFolderName = outputFolderName;
166
167                if (this.configuration.formatstatisticsoutput)
168                        this.serializer = new FormatedStringSerializer();
169                else
170                        this.serializer = new StringSerializer();
171
172                this.serializer.setDefaultNumberFormat(GridSchedulingSimulator.DFAULT_NUMBER_FORMAT);
173
174                this.resourceController = resourceController;
175                 jr = new JobRegistry("COMPUTING_GRID_0#BROKER");
176                init();
177        }
178
179        public void generateStatistics() {
180
181                this.startSimulationTime = DateTimeUtilsExt.getOffsetTime().getTimeInMillis();
182
183                this.endSimulationTime = DateTimeUtilsExt.currentTimeMillis();
184
185                long s = 0;
186                long e = 0;
187
188                log.info("gatherResourceStatistics");
189                s = System.currentTimeMillis();
190                gatherResourceStatistics();
191                e = System.currentTimeMillis();
192                log.info("time in sec: " + ((e - s) / 1000));
193               
194                log.info("gatherTaskStatistics");
195                s = System.currentTimeMillis();
196                gatherTaskStatistics();
197                e = System.currentTimeMillis();
198                log.info("time in sec: " + ((e - s) / 1000));
199
200                log.info("saveSimulationStatistics");
201                s = System.currentTimeMillis();
202                saveSimulationStatistics();
203                e = System.currentTimeMillis();
204                log.info("time in sec: " + ((e - s) / 1000));
205               
206                System.out.println("SIMULATION DURATION = " + (endSimulationTime - startSimulationTime) / 1000);
207        }
208
209
210        public String getOutputFolderName() {
211                return outputFolderName;
212        }
213
214        private void init() {
215
216                task_processorsMap = new HashMap<String, List<String>>();
217                accStats = new GSSAccumulatorsStats();
218        }
219
220        public void saveSimulationStatistics() {
221                PrintStream simulationStatsFile = null;
222                if (configuration.createsimulationstatistics) {
223                        try {
224                                File file = new File(outputFolderName + STATS_FILE_NAME_PREFIX + simulationIdentifier + "_"
225                                                + SIMULATION_STATISTICS_OUTPUT_FILE_NAME);
226                                simulationStatsFile = new PrintStream(new FileOutputStream(file));
227                        } catch (IOException e) {
228                                e.printStackTrace();
229                        }
230                }
231                if (simulationStatsFile != null) {
232                        Object txt = accStats.serialize(this.serializer);
233                        simulationStatsFile.println(txt);
234                }
235
236                if (simulationStatsFile != null) {
237                        simulationStatsFile.close();
238                }
239
240        }
241
242
243
244        /************* RESOURCE STATISTICS SECTION **************/
245        private void gatherResourceStatistics() {
246               
247               
248                //TEMPORARY CONFIGURATION SECTION
249                ResourceType [] resForAnalyze = {ResourceType.DATA_CENTER, ResourceType.COMPUTING_NODE, ResourceType.CPU};
250                HashMap<ResourceType, List<Stats>> type_stats = new HashMap<ResourceType, List<Stats>>();
251               
252                List<Stats> crStats = new ArrayList<Stats>();
253                crStats.add(Stats.textLoad);
254                crStats.add(Stats.chartLoad);
255                crStats.add(Stats.textEnergy);
256                crStats.add(Stats.chartEnergy);
257                type_stats.put(ResourceType.DATA_CENTER, crStats);
258               
259                List<Stats> cnStats = new ArrayList<Stats>();
260                cnStats.add(Stats.textLoad);
261                //cnStats.add(Stats.chartLoad);
262                cnStats.add(Stats.textEnergy);
263                //cnStats.add(Stats.chartEnergy);
264                type_stats.put(ResourceType.COMPUTING_NODE, cnStats);
265               
266                List<Stats> cpuStats = new ArrayList<Stats>();
267                cpuStats.add(Stats.textLoad);
268                //cpuStats.add(Stats.chartLoad);
269                cpuStats.add(Stats.textEnergy);
270                //cpuStats.add(Stats.chartEnergy);
271                type_stats.put(ResourceType.CPU, cpuStats);
272               
273               
274               
275                peGanttMap = new HashMap<String, TimetableEventSource>();
276                taskGanttMap = new HashMap<String, TimetableEventGroup>();
277               
278               
279                resourceLoadDiagrams = new HashMap<ResourceType, List<XYDataset>>();
280                resourceEnergyDiagrams = new HashMap<ResourceType, List<XYDataset>>();
281               
282                ganttDiagramPeTimetable = new Timetable(new FixedMillisecond(
283                                startSimulationTime), new FixedMillisecond(endSimulationTime));
284               
285                PrintStream resourceLoadStatsFile = null;
286                try {
287                        File file = new File(outputFolderName + STATS_FILE_NAME_PREFIX
288                                        + simulationIdentifier + "_"
289                                        + RESOURCEUSAGE_STATISTICS_OUTPUT_FILE_NAME);
290                        resourceLoadStatsFile = new PrintStream(new FileOutputStream(file));
291                } catch (IOException e) {
292                        resourceLoadStatsFile = null;
293                }
294               
295                PrintStream energyStatsFile = null;
296                try {
297                        File file = new File(outputFolderName + STATS_FILE_NAME_PREFIX
298                                        + simulationIdentifier + "_"
299                                        + ENERGYUSAGE_STATISTICS_OUTPUT_FILE_NAME);
300                        energyStatsFile = new PrintStream(new FileOutputStream(file));
301                } catch (IOException e) {
302                        energyStatsFile = null;
303                }
304               
305                basicResStats = gatherPEStats(JobRegistry.getAllocationHistory());
306                peStatsPostProcessing(basicResStats);
307                basicResLoad = calculatePELoad( basicResStats);
308
309                if (configuration.creatediagrams_processors) {
310                        createPEAppGanttDiagram(basicResStats);
311                }
312               
313                for(ResourceType resType: resForAnalyze){
314                        List<ComputingResource> resources = null;
315                        try {
316                                resources = (List<ComputingResource>) resourceController.getResources().getDescendantsByType(resType);
317                        } catch (Exception e) {
318                                continue;
319                        }
320                        if(type_stats.containsKey(resType)){
321                                Map<String, GSSAccumulator> energyCategoryStats = new TreeMap<String, GSSAccumulator>();
322                                Map<String, GSSAccumulator> loadCategoryStats = new TreeMap<String, GSSAccumulator>();
323                                for(ComputingResource resource: resources){
324                                        ResourceUsageStats resourceUsage = null;
325                                        ResourceEnergyStats energyUsage = null;
326                                        if(type_stats.get(resType).contains(Stats.textLoad)){
327                                                resourceUsage = gatherResourceLoadStats(resource, basicResStats);
328                                                resourceUsage.setMeanUsage(calculateResourceLoad(resource, basicResLoad));
329                                                if (resourceLoadStatsFile != null) {
330                                                        Object txt = resourceUsage.serialize(serializer);
331                                                        if( resType == ResourceType.DATA_CENTER)
332                                                                resourceLoadStatsFile.println(txt);
333                                                }
334                                        }
335                                        if(type_stats.get(resType).contains(Stats.chartLoad)){
336                                                if (configuration.creatediagrams_resources) {
337                                                        createResourceLoadDiagram(resourceUsage);
338                                                }
339                                        }
340                                        if(type_stats.get(resType).contains(Stats.textEnergy)){
341                                                energyUsage = gatherResourceEnergyStats(resource);
342                                                energyUsage.setMeanUsage(calculateEnergyLoad(energyUsage));
343                                                energyUsage.setSumUsage(energyUsage.getMeanUsage() * (endSimulationTime-startSimulationTime)/(3600*1000));
344                                                if (energyStatsFile != null) {
345                                                        Object txt = energyUsage.serialize(serializer);
346                                                        if( resType == ResourceType.DATA_CENTER)
347                                                                energyStatsFile.println(txt);
348                                                }
349                                        }
350                                        if(type_stats.get(resType).contains(Stats.chartEnergy)){
351
352                                                if (configuration.creatediagrams_energyusage) {
353                                                        createResourceEnergyGanttDiagram(energyUsage);
354                                                }
355                                        }
356                                       
357                                       
358                                        if(resType == ResourceType.COMPUTING_NODE){
359                                                ComputingNode compNode = (ComputingNode) resource;
360                                                if(energyCategoryStats.containsKey(resType+"#"+compNode.getCategory().getName())){
361                                                        GSSAccumulator acc = energyCategoryStats.get(resType+"#"+compNode.getCategory().getName());
362                                                        acc.add(energyUsage.meanUsage);
363                                                        energyCategoryStats.put(resType+"#"+compNode.getCategory().getName(), acc);
364                                                } else{
365                                                        GSSAccumulator acc = new GSSAccumulator();
366                                                        acc.add(energyUsage.meanUsage);
367                                                        energyCategoryStats.put(resType+"#"+compNode.getCategory().getName(), acc);
368                                                }
369                                               
370                                                if(loadCategoryStats.containsKey(resType+"#"+compNode.getCategory().getName())){
371                                                        GSSAccumulator acc = loadCategoryStats.get(resType+"#"+compNode.getCategory().getName());
372                                                        acc.add(resourceUsage.meanUsage);
373                                                        loadCategoryStats.put(resType+"#"+compNode.getCategory().getName(), acc);
374                                                } else{
375                                                        GSSAccumulator acc = new GSSAccumulator();
376                                                        acc.add(resourceUsage.meanUsage);
377                                                        loadCategoryStats.put(resType+"#"+compNode.getCategory().getName(), acc);
378                                                }
379                                        } else if(resType == ResourceType.CPU){
380                                                Processor proc = (Processor)resource;
381                                                if(energyCategoryStats.containsKey(resType+"#"+proc.getComputingNode().getCategory().getName())){
382                                                        GSSAccumulator acc = energyCategoryStats.get(resType+"#"+proc.getComputingNode().getCategory().getName());
383                                                        acc.add(energyUsage.meanUsage);
384                                                        energyCategoryStats.put(resType+"#"+proc.getComputingNode().getCategory().getName(), acc);
385                                                } else{
386                                                        GSSAccumulator acc = new GSSAccumulator();
387                                                        acc.add(energyUsage.meanUsage);
388                                                        energyCategoryStats.put(resType+"#"+proc.getComputingNode().getCategory().getName(), acc);
389                                                }
390                                               
391                                                if(loadCategoryStats.containsKey(resType+"#"+proc.getComputingNode().getCategory().getName())){
392                                                        GSSAccumulator acc = loadCategoryStats.get(resType+"#"+proc.getComputingNode().getCategory().getName());
393                                                        acc.add(resourceUsage.meanUsage);
394                                                        loadCategoryStats.put(resType+"#"+proc.getComputingNode().getCategory().getName(), acc);
395                                                } else{
396                                                        GSSAccumulator acc = new GSSAccumulator();
397                                                        acc.add(resourceUsage.meanUsage);
398                                                        loadCategoryStats.put(resType+"#"+proc.getComputingNode().getCategory().getName(), acc);
399                                                }
400                                        }
401                                }
402                               
403                                if(energyCategoryStats.size()>0)
404                                {
405                                        energyStatsFile.println("\n=========BY CATEGORY===========");
406                                        for(String key: energyCategoryStats.keySet()){
407                                                GSSAccumulator acc = energyCategoryStats.get(key);
408                                                energyStatsFile.println(key + "- mean: "  +acc.getMean()+ " sum: " +acc.getMean()*(endSimulationTime-startSimulationTime)/(3600*1000)*acc.getCount());
409                                        }
410                                        energyStatsFile.println("\n\n");
411                                }
412                               
413                                if(loadCategoryStats.size()>0)
414                                {
415                                        resourceLoadStatsFile.println("\n=========BY CATEGORY===========");
416                                        for(String key: loadCategoryStats.keySet()){
417                                                GSSAccumulator acc = loadCategoryStats.get(key);
418                                                resourceLoadStatsFile.println(key + "- mean: "  +acc.getMean());
419                                        }
420                                        resourceLoadStatsFile.println("\n\n");
421                                }
422
423                        }
424                }
425               
426                saveResourceGanttDiagrams();
427                createAccumulatedResourceSimulationStatistic();
428                if (energyStatsFile != null) {
429                        energyStatsFile.close();
430                }
431                if (resourceLoadStatsFile != null) {
432                        resourceLoadStatsFile.close();
433                }
434       
435        }
436       
437        private void peStatsPostProcessing(Map<String, List<ResStat>> basicResStats){
438                ResourceType resType = null;
439
440                for(String key: basicResStats.keySet()){
441                        List<ResStat> resStats = basicResStats.get(key);
442                        resType = resStats.get(0).getResType();
443                        break;
444                }
445                List<ComputingResource> resources = null;
446                try {
447                        resources = (List<ComputingResource>) resourceController.getResources().getDescendantsByType(resType);
448                } catch (Exception e) {
449                        return;
450                }
451                for(ComputingResource resource: resources){
452                        if(!basicResStats.containsKey(resource.getName())){
453                                basicResStats.put(resource.getName(), new ArrayList<ResStat>());
454                        }
455                }
456        }
457        private Map<String, List<ResStat>> gatherPEStats(Map<Integer, Map<String, Object>> history) {
458
459                Map<String, List<ResStat>> basicResStats = new TreeMap<String, List<ResStat>>(new MapPEIdComparator());
460               
461                for (Integer executableID : history.keySet()) {
462
463                        Map<String, Object> historyItem = (Map<String, Object>) history.get(executableID);
464                        List<ResourceHistoryItem> resHistItemList = (List<ResourceHistoryItem>) historyItem.get(GssimConstants.RESOURCES);
465                        Map<ResourceParameterName, ResourceUnit> res = resHistItemList.get(resHistItemList.size() - 1).getResourceUnits();
466                        ResourceUnit resUnit = res.get(ResourceParameterName.PROCESSINGELEMENTS);
467                        ProcessingElements pes = (ProcessingElements) resUnit ;
468                       
469                        for(ComputingResource pe: pes){
470                                String peName = pe.getName();
471                                long startDate = ((DateTime) historyItem.get(GssimConstants.START_TIME)).getMillis();
472                                long endDate = ((DateTime) historyItem.get(GssimConstants.END_TIME)).getMillis();
473                                JobRegistry jr = new JobRegistry("stats");
474                                ExecTaskInterface execTask = jr.getTaskExecutable(executableID);
475                                String uniqueTaskID = execTask.getJobId() + "_" + execTask.getId();
476                               
477                                ResStat resStat = new ResStat(peName, pe.getType(), startDate, endDate, uniqueTaskID);
478                               
479                                List<ResStat> resStats = basicResStats.get(peName);
480                                if (resStats == null) {
481                                        resStats = new ArrayList<ResStat>();
482                                        resStats.add(resStat);
483                                        basicResStats.put(peName, resStats);
484                                } else {
485                                        resStats.add(resStat);
486                                }
487
488                                List<String> peNames = task_processorsMap.get(uniqueTaskID);
489                                if (peNames == null) {
490                                        peNames = new ArrayList<String>();
491                                        peNames.add(peName);
492                                        task_processorsMap.put(uniqueTaskID, peNames);
493                                } else {
494                                        peNames.add(peName);
495                                }
496                        }
497                }
498                return basicResStats;
499        }
500       
501        private ResourceUsageStats gatherResourceLoadStats(ComputingResource resource, Map<String,List<ResStat>> basicStats) {
502                ResourceUsageStats usageStats = new ResourceUsageStats(resource.getName(), resource.getType(), "resourceLoadStats");
503                for(String resName: basicStats.keySet()){
504                        try {
505                                if(resource.getDescendantsByName(resName) != null || resource.getName().compareTo(resName) == 0){
506                                        createResourceLoadData(usageStats, basicStats.get(resName));
507                                }
508                        } catch (ResourceException e) {
509                                // TODO Auto-generated catch block
510                                e.printStackTrace();
511                        }
512                }
513                return usageStats;
514        }
515       
516        private TreeMap<Long, Integer> createResourceLoadData(ResourceUsageStats usageStats, List<ResStat> resStats) {
517
518                TreeMap<Long, Integer> ganttData = (TreeMap)usageStats.getUsage();
519                for (ResStat resStat : resStats) {
520                       
521                        long start_time = resStat.getStartDate();
522                        long end_time = resStat.getEndDate();
523                        if (end_time > start_time) {
524                                Integer end = ganttData.get(end_time);
525                                if (end == null) {
526                                        ganttData.put(end_time, 0);
527                                        Long left = getLeftKey(ganttData, end_time);
528                                        if (left != null) {
529                                                Integer leftValue = ganttData.get(left);
530                                                ganttData.put(end_time, leftValue);
531                                        }
532                                }
533
534                                Integer start = ganttData.get(start_time);
535                                if (start == null) {
536                                        ganttData.put(start_time, 0);
537                                        Long left = getLeftKey(ganttData, start_time);
538                                        if (left != null) {
539                                                Integer leftValue = ganttData.get(left);
540                                                ganttData.put(start_time, leftValue);
541                                        }
542                                }
543
544                                SortedMap<Long, Integer> sm = ganttData.subMap(start_time,
545                                                end_time);
546                                for (Long key : sm.keySet()) {
547                                        Integer keyVal = ganttData.get(key);
548                                        ganttData.put(key, keyVal + 1);
549                                }
550                        }
551                }
552                return ganttData;
553        }
554
555        private Long getLeftKey(TreeMap<Long, Integer> ganttData, Long toKey) {
556
557                SortedMap<Long, Integer> sm = ganttData.headMap(toKey);
558                if (sm.isEmpty()) {
559                        return null;
560                }
561                return sm.lastKey();
562        }
563       
564       
565        private ResourceEnergyStats gatherResourceEnergyStats(ComputingResource resource) {
566                double power = 0;
567                ResourceEnergyStats resEnergyUsage = new ResourceEnergyStats(resource.getName(), resource.getType(), "resourceEnergyStats");
568                Map<Long, Double> usage = resEnergyUsage.getEnergy();
569               
570                ExtensionList extensionList = resource.getExtensionList();
571                if(extensionList != null){
572                        for (Extension extension : extensionList) {
573                                if (extension.getType() == ExtensionType.ENERGY_EXTENSION) {
574                                        EnergyExtension ee = (EnergyExtension)extension;
575                                        List<PowerUsage> powerUsage = ee.getPowerUsageHistory();
576                                        if(powerUsage.size()==0)
577                                                break;
578                                        long lastTime = DateTimeUtilsExt.getOffsetTime().getTimeInMillis();
579                                        long endSimulationTime = DateTimeUtilsExt.currentTimeMillis();
580                                        double lastPower = 0;
581                                        powerUsage.add(new PowerUsage(endSimulationTime, ee.getPowerUsageHistory().get(ee.getPowerUsageHistory().size()-1).getValue()));
582                                        for(PowerUsage pu:powerUsage){
583                                                usage.put(pu.getTimestamp(), pu.getValue());
584                                               
585                                        ///     System.out.println(resource.getName() + ":"+new DateTime(pu.getTimestamp())+";"+pu.getValue());
586                                                power = power + (pu.getTimestamp() - lastTime) * lastPower/ (3600 * 1000);
587                                                lastPower = pu.getValue();
588                                                lastTime = pu.getTimestamp();
589                                        }
590                                }
591                        }
592                }
593                //System.out.println(power);
594                return resEnergyUsage;
595        }
596       
597        private void createResourceEnergyGanttDiagram(ResourceEnergyStats energyUsage) {
598
599                XYDataset dataset = createResourceEnergyGanttDataSet(energyUsage,
600                                startSimulationTime, endSimulationTime);
601               
602                List<XYDataset> energyDiagram = resourceEnergyDiagrams.get(energyUsage.getResourceType());
603                if(energyDiagram == null){
604                        energyDiagram = new ArrayList<XYDataset>();
605                        energyDiagram.add(dataset);
606                        resourceEnergyDiagrams.put(energyUsage.getResourceType(), energyDiagram);
607                } else {
608                        energyDiagram.add(dataset);
609                }
610
611        }
612
613        private XYDataset createResourceEnergyGanttDataSet(
614                        ResourceEnergyStats energyUsage, long start, long end) {
615
616                TreeMap<Long, Double> ganttdata = createResourceEnergyGanttData(energyUsage);
617                XYSeriesCollection dataset = new XYSeriesCollection();
618                XYSeries data = new XYSeries(energyUsage.getResourceName(), false, true);
619                //data.add(start, 0);
620                for (Long key : ganttdata.keySet()) {
621                        Double val = ganttdata.get(key);
622                        data.add(key, val);
623                }
624                data.add(end, 0);
625                dataset.addSeries(data);
626                return dataset;
627        }
628
629        private TreeMap<Long, Double> createResourceEnergyGanttData(
630                        ResourceEnergyStats energyUsage) {
631
632                Map<Long, Double> energy = energyUsage.getEnergy();
633                TreeMap<Long, Double> ganttData = new TreeMap<Long, Double>();
634                for (Long euKey : energy.keySet()) {
635
636                        ganttData.put(euKey, energy.get(euKey));
637                }
638                return ganttData;
639        }
640
641
642        private boolean saveResourceGanttDiagrams() {
643                JFreeChart resourceDiagram = null;
644                JFreeChart peDiagram = null;
645                JFreeChart resourceEnergyDiagram = null;
646                if (!generateDiagrams)
647                        return false;
648
649                String fileName = new File(outputFolderName, DIAGRAMS_FILE_NAME_PREFIX
650                                + simulationIdentifier + "_").getAbsolutePath();
651
652                String chartName = "Gantt diagram for "
653                                + GridSchedulingSimulator.SIMULATOR_NAME;
654                String simulationTime = "Simulation time";
655                Title subtitle = new TextTitle("created for \"" + simulationIdentifier
656                                + "\" at " + Calendar.getInstance().getTime().toString());
657
658               
659                if (configuration.creatediagrams_processors) {
660                        peDiagram = getPeGanttDiagram(chartName, subtitle,
661                                        simulationTime);
662                        if (!saveCategoryChart(peDiagram, fileName + "Processing_Elements",
663                                        "{0}"))
664                                return false;
665                }
666
667                if (configuration.creatediagrams_resources) {
668                        for(ResourceType resType: resourceLoadDiagrams.keySet()){
669                                resourceDiagram = getResourcesLoadDiagram(resType, chartName, subtitle,
670                                                simulationTime);
671                                if (!saveXYPlotChart(resourceDiagram, fileName + "Resources Load - "+resType))
672                                        return false;
673                        }
674
675                }
676                if (configuration.creatediagrams_energyusage) {
677                        for(ResourceType resType: resourceEnergyDiagrams.keySet()){
678                                resourceEnergyDiagram = getResourcesEnergyDiagram(resType, chartName,
679                                                subtitle, simulationTime);
680                                if (!saveXYPlotChart(resourceEnergyDiagram, fileName + "Energy - "+resType))
681                                        return false;
682                        }
683                }
684                return true;
685        }
686       
687        private JFreeChart getResourcesLoadDiagram(ResourceType resType, String chartName, Title subtitle,
688                        String simulationTime) {
689                String cpu = "CPU";
690                boolean urls = false;
691                boolean tooltip = true;
692                boolean legend = true;
693                CombinedDomainXYPlot cPlot = new CombinedDomainXYPlot();
694                DateAxis xAxis = new DateAxis(simulationTime);
695                JFreeChart chart = null;
696
697                List<XYDataset> loadDiagram = resourceLoadDiagrams.get(resType);
698                for (XYDataset dataset : loadDiagram) {
699                        JFreeChart tChart = ChartFactory.createXYStepAreaChart("", "",
700                                null, dataset, PlotOrientation.VERTICAL, legend, tooltip,
701                                urls);
702                        XYPlot tPlot = tChart.getXYPlot();
703                        NumberAxis yAxis = new NumberAxis(cpu);
704                        yAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
705                        tPlot.setRangeAxis(yAxis);
706                        XYStepAreaRenderer rend = (XYStepAreaRenderer) tPlot.getRenderer();
707                        rend.setShapesVisible(false);
708                        cPlot.add(tPlot);
709                }
710                cPlot.setDomainAxis(xAxis);
711                cPlot.setDomainAxisLocation(AxisLocation.TOP_OR_LEFT);
712                chart = new JFreeChart(chartName, cPlot);
713                chart.addSubtitle(subtitle);
714                return chart;
715        }
716
717        private JFreeChart getResourcesEnergyDiagram(ResourceType resType, String chartName,
718                        Title subtitle, String simulationTime) {
719                String energy = "ENERGY [W]";
720                boolean urls = false;
721                boolean tooltip = true;
722                boolean legend = true;
723                CombinedDomainXYPlot cPlot = new CombinedDomainXYPlot();
724                DateAxis xAxis = new DateAxis(simulationTime);
725
726                List<XYDataset> energyDiagram = resourceEnergyDiagrams.get(resType);
727                for (XYDataset dataset : energyDiagram) {
728
729                        JFreeChart tChart = ChartFactory.createXYStepAreaChart("", "",
730                                        null, dataset, PlotOrientation.VERTICAL, legend, tooltip,
731                                        urls);
732
733                        XYPlot tPlot = tChart.getXYPlot();
734                        NumberAxis yAxis = new NumberAxis(energy);
735                        yAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
736                        tPlot.setRangeAxis(yAxis);
737                        XYStepAreaRenderer rend = (XYStepAreaRenderer) tPlot.getRenderer();
738                        rend.setShapesVisible(false);
739                        cPlot.add(tPlot);
740                }
741                cPlot.setDomainAxis(xAxis);
742                cPlot.setDomainAxisLocation(AxisLocation.TOP_OR_LEFT);
743                JFreeChart chart = new JFreeChart(chartName, cPlot);
744                chart.addSubtitle(subtitle);
745                return chart;
746        }
747       
748       
749        private JFreeChart getPeGanttDiagram(String chartName, Title subtitle,
750                        String simulationTime) {
751                String processors = "Processing Elements";
752                boolean tooltip = true;
753                boolean legend = true;
754                JFreeChart chart = TimetableChartFactory.createTimetableChart(
755                                chartName, processors, simulationTime,
756                                ganttDiagramPeTimetable, legend, tooltip);
757                chart.addSubtitle(subtitle);
758                TimetableRenderer rend = (TimetableRenderer) chart.getCategoryPlot()
759                                .getRenderer();
760                rend.setBackgroundBarPaint(null);
761                return chart;
762        }
763       
764       
765        private boolean saveXYPlotChart(JFreeChart c, String fileName) {
766                c.setNotify(false);
767                c.setAntiAlias(true);
768                c.setTextAntiAlias(true);
769                c.setBorderVisible(false);
770
771                int height = 900;
772
773                CombinedDomainXYPlot cPlot = (CombinedDomainXYPlot) c.getPlot();
774                int nPlots = cPlot.getSubplots().size();
775
776                if (nPlots > 3) {
777                        height = nPlots * 300;
778                }
779                int width = GANTT_WIDTH;
780
781                if (configuration.creatediagrams_resources_scale != -1)
782                        width = (int) ((endSimulationTime - startSimulationTime) * configuration.creatediagrams_resources_scale);
783                ChartRenderingInfo info = new ChartRenderingInfo();
784                File f = new File(fileName + "." + ImageFormat.PNG);
785                final String gssimSubtitle = "Created by "
786                                + GridSchedulingSimulator.SIMULATOR_NAME
787                                + " http://www.gssim.org/";
788                c.addSubtitle(new TextTitle(gssimSubtitle));
789                boolean encodeAlpha = false;
790                int compression = 9;// values 0-9
791                try {
792                        ChartUtilities.saveChartAsPNG(f, c, width, height, info,
793                                        encodeAlpha, compression);
794                } catch (IOException e) {
795                        e.printStackTrace();
796                        return false;
797                }
798                return true;
799        }
800       
801        private void createPEGanttDiagram(Map<String,List<ResStat>> basicResStats) {
802                for(String peName: basicResStats.keySet()){
803                        TimetableEventSource pe = new TimetableEventSource(peName);
804                        ganttDiagramPeTimetable.addEventSource(pe);
805                        peGanttMap.put(peName, pe);
806                        for(ResStat resStat: basicResStats.get(peName)){
807
808                                pe = peGanttMap.get(resStat.getPeName());
809                                if(pe == null){
810                                        //pe = new TimetableEventSource(resStat.getPeName());
811                                //      ganttDiagramPeTimetable.addEventSource(pe);
812                                //      peGanttMap.put(resStat.getPeName(), pe);
813                                }
814                                TimetableEventGroup task = taskGanttMap.get(resStat.getTaskID());
815                                long startDate = resStat.getStartDate();
816                                long endDate = resStat.getEndDate();
817                                if (task == null) {
818                                        task = new TimetableEventGroup(resStat.getTaskID());
819                                        taskGanttMap.put(resStat.getTaskID(), task);
820                                        ganttDiagramPeTimetable.addEventGroup(task);
821                                }
822                                ganttDiagramPeTimetable.addEvent(pe, task,
823                                                new FixedMillisecond(startDate), new FixedMillisecond(endDate));
824                        }
825                }
826        }
827       
828        private void createPEAppGanttDiagram(Map<String,List<ResStat>> basicResStats) {
829                for(String peName: basicResStats.keySet()){
830                        TimetableEventSource pe = new TimetableEventSource(peName);
831                        ganttDiagramPeTimetable.addEventSource(pe);
832                        peGanttMap.put(peName, pe);
833                        for(ResStat resStat: basicResStats.get(peName)){
834
835                                pe = peGanttMap.get(resStat.getPeName());
836                                if(pe == null){
837                                        //pe = new TimetableEventSource(resStat.getPeName());
838                                //      ganttDiagramPeTimetable.addEventSource(pe);
839                                //      peGanttMap.put(resStat.getPeName(), pe);
840                                }
841                                String taskID = resStat.getTaskID().split("_")[0];
842                                Integer taskGroupID = Integer.parseInt(taskID) % 4;
843                                TimetableEventGroup task = taskGanttMap.get(taskGroupID);
844                                long startDate = resStat.getStartDate();
845                                long endDate = resStat.getEndDate();
846                                if (task == null) {
847                                        task = new TimetableEventGroup(taskGroupID.toString());
848                                        taskGanttMap.put(taskGroupID.toString(), task);
849                                        ganttDiagramPeTimetable.addEventGroup(task);
850                                }
851                                ganttDiagramPeTimetable.addEvent(pe, task,
852                                                new FixedMillisecond(startDate), new FixedMillisecond(endDate));
853                        }
854                }
855        }
856       
857       
858
859        private void createResourceLoadDiagram(ResourceUsageStats resStats) {
860
861                XYDataset dataset = createResourceLoadDataSet(resStats);
862
863                List<XYDataset> loadDiagram = resourceLoadDiagrams.get(resStats.getResourceType());
864                if(loadDiagram == null){
865                        loadDiagram = new ArrayList<XYDataset>();
866                        loadDiagram.add(dataset);
867                        resourceLoadDiagrams.put(resStats.getResourceType(), loadDiagram);
868                } else {
869                        loadDiagram.add(dataset);
870                }
871        }
872
873        private XYDataset createResourceLoadDataSet(ResourceUsageStats resStats) {
874
875                XYSeriesCollection dataset = new XYSeriesCollection();
876                XYSeries data = new XYSeries(resStats.resourceName, false, true);
877                Map<Long, Integer> usage = resStats.getUsage();
878               
879                for (Long key : usage.keySet()) {
880                        Integer val = usage.get(key);
881                        data.add(key, val);
882                }
883                dataset.addSeries(data);
884                return dataset;
885        }
886
887        private void createAccumulatedResourceSimulationStatistic() {
888
889                ComputingResource resource = resourceController.getResources();
890
891                for(ComputingResource child :resource.getChildren()){
892                        double load = calculateResourceLoad(child, basicResLoad);
893                        accStats.meanTotalLoad.add(load);
894                        //ResourceEnergyStats energyUsage = gatherResourceEnergyStats(child);
895                        //energyUsage.setMeanUsage(calculateEnergyLoad(energyUsage));
896                        //accStats.meanEnergyUsage.add(energyUsage.meanUsage);
897                }
898
899        }
900
901        private HashMap<String, Double> calculatePELoad(Map<String,List<ResStat>> basicResStats){
902                HashMap<String, Double> peLoad = new HashMap<String, Double>();
903                for(String resName: basicResStats.keySet()){
904                        List<ResStat> resStats = basicResStats.get(resName);
905                        double sum = 0;
906                        for(ResStat resStat:resStats){
907                                sum += (resStat.endDate-resStat.startDate);
908                        }
909                        double load = sum/(endSimulationTime-startSimulationTime);
910                        peLoad.put(resName, load);
911                }
912                return peLoad;
913        }
914       
915        private  Double calculateResourceLoad(ComputingResource resource, HashMap<String, Double> peLoad ){
916                int peCnt = 0;
917                double sum = 0;
918                for(String resName: peLoad.keySet()){
919
920                        try {
921                                if(resource.getDescendantsByName(resName)!= null || resource.getName().compareTo(resName)==0){
922                                        Double load = peLoad.get(resName);
923                                        sum += load;
924                                        peCnt++;
925                                }
926                        } catch (ResourceException e) {
927                                // TODO Auto-generated catch block
928                                e.printStackTrace();
929                        }
930                }
931               
932                return sum/peCnt;
933        }
934       
935        private double calculateEnergyLoad(ResourceEnergyStats resEnergyStats ){
936                double meanEnergyUsage = 0;
937                long time = 0;
938                double usage = 0;
939                Map<Long, Double> enUsage = resEnergyStats.getEnergy();
940                for (Long key : enUsage.keySet()) {
941                       
942                        if (time != 0) {
943                                meanEnergyUsage += (usage * (key - time))
944                                                / (endSimulationTime - startSimulationTime);
945
946                                time = key;
947                        } else {
948                                time = key;
949                        }
950                        usage = (double) enUsage.get(key);
951                }
952                return meanEnergyUsage;
953        }
954       
955        /*private void createPEGanttDiagram(String peName,
956                        String uniqueTaskID, Map<String, Object> historyItem) {
957                TimetableEventSource pe = peGanttMap.get(peName);
958                if(pe == null){
959                        pe = new TimetableEventSource(peName);
960                        ganttDiagramPETimetable.addEventSource(pe);
961                        peGanttMap.put(peName, pe);
962                }
963                TimetableEventGroup task = taskGanttMap.get(uniqueTaskID);
964                long startDate = ((DateTime) historyItem.get(GssimConstants.START_TIME))
965                                .getMillis();
966                long endDate = ((DateTime) historyItem.get(GssimConstants.END_TIME))
967                                .getMillis();
968                if (task == null) {
969                        task = new TimetableEventGroup(uniqueTaskID);
970                        taskGanttMap.put(uniqueTaskID, task);
971                        ganttDiagramPETimetable.addEventGroup(task);
972                }
973                ganttDiagramPETimetable.addEvent(pe, task,
974                                new FixedMillisecond(startDate), new FixedMillisecond(endDate));
975        }*/
976       
977
978
979        /************* TASK STATISTICS SECTION **************/
980        public void gatherTaskStatistics() {
981
982                List<JobInterface<?>> jobs = users.getAllReceivedJobs();
983                Collections.sort(jobs, new JobIdComparator());
984
985                ganttDiagramTaskSeriesCollection = new TaskSeriesCollection();
986                ganttDiagramWaitingTimeSeriesCollection = new TaskSeriesCollection();
987               
988                HashMap<String, List<TaskStats>> cat_taskStats = new HashMap<String, List<TaskStats>>();
989               
990
991                PrintStream taskStatsFile = null;
992                try {
993                        File file = new File(outputFolderName + STATS_FILE_NAME_PREFIX + simulationIdentifier + "_"
994                                        + RAW_TASKS_STATISTICS_OUTPUT_FILE_NAME);
995                        taskStatsFile = new PrintStream(new FileOutputStream(file));
996                } catch (IOException e) {
997                        taskStatsFile = null;
998                }
999
1000                PrintStream taskCategoryStatsFile = null;
1001                try {
1002                        File file = new File(outputFolderName + STATS_FILE_NAME_PREFIX + simulationIdentifier + "_"
1003                                        + CATEGORY_TASKS_STATISTICS_OUTPUT_FILE_NAME);
1004                        taskCategoryStatsFile = new PrintStream(new FileOutputStream(file));
1005                } catch (IOException e) {
1006                        taskCategoryStatsFile = null;
1007                }
1008               
1009                PrintStream jobStatsFile = null;
1010                if (configuration.createjobsstatistics) {
1011                        try {
1012                                File file = new File(outputFolderName + STATS_FILE_NAME_PREFIX + simulationIdentifier + "_"
1013                                                + JOBS_STATISTICS_OUTPUT_FILE_NAME);
1014                                jobStatsFile = new PrintStream(new FileOutputStream(file));
1015                        } catch (IOException e) {
1016                                jobStatsFile = null;
1017                        }
1018                }
1019
1020                for (int i = 0; i < jobs.size(); i++) {
1021                        Job job = (Job) jobs.get(i);
1022
1023                        //List<TaskInterface> execList = JobRegistry.getInstance("COMPUTING_GRID_0#BROKER").getAllSubmittedTasks();
1024                        List<AbstractExecutable> execList = jr.getJobExecutables(job.getId());
1025                        List<TaskStats> taskStatsList = new ArrayList<TaskStats>();
1026
1027                        this.serializer.setFieldSeparator(TASK_SEPARATOR);
1028
1029                        for (int j = 0; j < execList.size(); j++) {
1030
1031                                AbstractExecutable task = (AbstractExecutable) execList.get(j);
1032
1033                                TaskStats taskStats = createTaskStats(task);
1034                                if (taskStats != null && taskStatsFile != null) {
1035                                        Object txt = taskStats.serialize(serializer);
1036                                        taskStatsFile.println(txt);
1037                                }
1038                                if (taskStats != null && taskStats.getExecFinishDate() != -1) {
1039                                        if (configuration.createsimulationstatistics) {
1040                                                createAccumulatedTaskSimulationStatistic(taskStats);
1041                                        }
1042                                        allTasksFinished &= task.isFinished();
1043                                        if (generateDiagrams) {
1044                                                if (configuration.creatediagrams_tasks)
1045                                                        createTaskDiagramData(task);
1046                                                if (configuration.creatediagrams_taskswaitingtime)
1047                                                        createTaskWaitingTimeDiagramData(task);
1048
1049                                        }
1050                                        taskStatsList.add(taskStats);
1051                                }
1052                               
1053                                String taskID = task.getJobId();
1054                                Integer taskGroupID = Integer.parseInt(taskID) % 4;
1055                               
1056                                List<TaskStats> taskCatStatsList= cat_taskStats.get(taskGroupID.toString());
1057
1058                                if (taskCatStatsList == null) {
1059                                        taskCatStatsList = new ArrayList<TaskStats>();
1060                                        cat_taskStats.put(taskGroupID.toString(), taskCatStatsList);
1061                                }
1062                                taskCatStatsList.add(taskStats);
1063                               
1064
1065                        }
1066                        if (configuration.createjobsstatistics && taskStatsList.size() > 0) {
1067
1068                                this.serializer.setFieldSeparator(JOB_SEPARATOR);
1069
1070                                JobStats jobStats = createJobStats(taskStatsList);
1071                                if (jobStatsFile != null) {
1072                                        Object txt = jobStats.serialize(serializer);
1073                                        jobStatsFile.println(txt);
1074                                }
1075                        }
1076                }
1077               
1078                for(String catID: cat_taskStats.keySet()){
1079                        TaskCategoryStats taskCatStats = createTaskCategoryStats(cat_taskStats.get(catID));
1080                        if (taskCategoryStatsFile != null) {
1081                                Object txt = taskCatStats.serialize(serializer);
1082                                taskCategoryStatsFile.println(txt);
1083                        }
1084                }
1085
1086               
1087                if (configuration.createsimulationstatistics) {
1088                        accStats.makespan.add(maxCj);
1089                        accStats.delayedTasks.add(numOfdelayedTasks);
1090                        accStats.failedRequests.add(users.getAllSentTasks().size() - users.getFinishedTasksCount());
1091
1092                }
1093
1094                saveTaskGanttDiagrams();
1095
1096                if (taskStatsFile != null) {
1097                        taskStatsFile.close();
1098                }
1099                if (jobStatsFile != null) {
1100                        jobStatsFile.close();
1101                }
1102        }
1103
1104        private TaskStats createTaskStats(AbstractExecutable task) {
1105                TaskStats taskStats = new TaskStats(task, startSimulationTime);
1106
1107                String uniqueTaskID = taskStats.getJobID() + "_" + taskStats.getTaskID();
1108
1109                taskStats.setProcessorsName(task_processorsMap.get(uniqueTaskID));
1110
1111                return taskStats;
1112        }
1113
1114        private TaskCategoryStats createTaskCategoryStats(List<TaskStats> tasksStats) {
1115
1116                String taskID = ((TaskStats) tasksStats.get(0)).getJobID();
1117                String catID = String.valueOf(Integer.parseInt(taskID) % 4);
1118                TaskCategoryStats taskCatStats = new TaskCategoryStats(catID);
1119                double maxCj = 0;
1120
1121                for (int i = 0; i < tasksStats.size(); i++) {
1122
1123                        TaskStats task = (TaskStats) tasksStats.get(i);
1124                        taskCatStats.meanTaskStartTime.add(task.getStartTime());
1125                        taskCatStats.meanTaskCompletionTime.add(task.getCompletionTime());
1126                        maxCj = Math.max(maxCj, task.getCompletionTime());
1127                        taskCatStats.meanTaskExecutionTime.add(task.getExecutionTime());
1128                        taskCatStats.meanTaskWaitingTime.add(task.getWaitingTime());
1129                        taskCatStats.meanTaskFlowTime.add(task.getFlowTime());
1130                        taskCatStats.meanTaskGQ_WaitingTime.add(task.getGQ_WaitingTime());
1131                        taskCatStats.lateness.add(task.getLateness());
1132                        taskCatStats.tardiness.add(task.getTardiness());
1133                }
1134                taskCatStats.makespan.add(maxCj);
1135
1136                return taskCatStats;
1137        }
1138       
1139        private JobStats createJobStats(List<TaskStats> tasksStats) {
1140
1141                String jobID = ((TaskStats) tasksStats.get(0)).getJobID();
1142                JobStats jobStats = new JobStats(jobID);
1143                double maxCj = 0;
1144
1145                for (int i = 0; i < tasksStats.size(); i++) {
1146
1147                        TaskStats task = (TaskStats) tasksStats.get(i);
1148                        jobStats.meanTaskStartTime.add(task.getStartTime());
1149                        jobStats.meanTaskCompletionTime.add(task.getCompletionTime());
1150                        maxCj = Math.max(maxCj, task.getCompletionTime());
1151                        jobStats.meanTaskExecutionTime.add(task.getExecutionTime());
1152                        jobStats.meanTaskWaitingTime.add(task.getWaitingTime());
1153                        jobStats.meanTaskFlowTime.add(task.getFlowTime());
1154                        jobStats.meanTaskGQ_WaitingTime.add(task.getGQ_WaitingTime());
1155                        jobStats.lateness.add(task.getLateness());
1156                        jobStats.tardiness.add(task.getTardiness());
1157                }
1158                jobStats.makespan.add(maxCj);
1159
1160                return jobStats;
1161        }
1162
1163        private void createAccumulatedTaskSimulationStatistic(TaskStats taskStats) {
1164                accStats.meanTaskFlowTime.add(taskStats.getFlowTime());
1165                accStats.meanTaskExecutionTime.add(taskStats.getExecutionTime());
1166                accStats.meanTaskCompletionTime.add(taskStats.getCompletionTime());
1167                accStats.meanTaskWaitingTime.add(taskStats.getWaitingTime());
1168                accStats.meanTaskStartTime.add(taskStats.getStartTime());
1169
1170                accStats.lateness.add(taskStats.getLateness());
1171                accStats.tardiness.add(taskStats.getTardiness());
1172
1173                if (taskStats.getExecFinishDate() == -1) {
1174                        numOfNotExecutedTasks++;
1175                }
1176                if (taskStats.getTardiness() > 0.0) {
1177                        numOfdelayedTasks++;
1178                }
1179
1180                maxCj = Math.max(maxCj, taskStats.getCompletionTime());
1181        }
1182
1183        private void createTaskDiagramData(AbstractExecutable task) {
1184                String uniqueTaskID = task.getJobId() + "_" + task.getId();
1185
1186                String resIDlist[] = task.getAllResourceName();
1187                String resID = resIDlist[resIDlist.length - 1];
1188
1189                long execStartTime = Double.valueOf(task.getExecStartTime()).longValue() * 1000;
1190                long execEndTime = Double.valueOf(task.getFinishTime()).longValue() * 1000;
1191
1192                TaskSeries taskRes = ganttDiagramTaskSeriesCollection.getSeries(resID);
1193                if (taskRes == null) {
1194                        taskRes = new TaskSeries(resID);
1195                        ganttDiagramTaskSeriesCollection.add(taskRes);
1196                }
1197                org.jfree.data.gantt.Task ganttTask = new org.jfree.data.gantt.Task(uniqueTaskID, new Date(execStartTime),
1198                                new Date(execEndTime));
1199                if (!task.isFinished()) {
1200                        ganttTask.setPercentComplete(1.0);
1201                }
1202                taskRes.add(ganttTask);
1203        }
1204
1205        private void createTaskWaitingTimeDiagramData(AbstractExecutable task) {
1206                String uniqueTaskID = task.getJobId() + "_" + task.getId();
1207
1208                String resIDlist[] = task.getAllResourceName();
1209                String resID = resIDlist[resIDlist.length - 1];
1210
1211                long execStartTime = Double.valueOf(task.getExecStartTime()).longValue() * 1000;
1212                long execEndTime = Double.valueOf(task.getFinishTime()).longValue() * 1000;
1213
1214                TaskSeries waitRes = ganttDiagramWaitingTimeSeriesCollection.getSeries(resID);
1215                if (waitRes == null) {
1216                        waitRes = new TaskSeries(resID);
1217                        ganttDiagramWaitingTimeSeriesCollection.add(waitRes);
1218                }
1219
1220                long sub = Double.valueOf(task.getSubmissionTime()).longValue() * 1000;
1221                org.jfree.data.gantt.Task wait_exec = new org.jfree.data.gantt.Task(uniqueTaskID, new Date(sub), new Date(
1222                                execEndTime));
1223                org.jfree.data.gantt.Task exec = new org.jfree.data.gantt.Task(uniqueTaskID, new Date(execStartTime), new Date(
1224                                execEndTime));
1225                if (!task.isFinished()) {
1226                        exec.setPercentComplete(1.0);
1227                }
1228                wait_exec.addSubtask(wait_exec);
1229                wait_exec.addSubtask(exec);
1230                waitRes.add(wait_exec);
1231        }
1232
1233        private boolean saveTaskGanttDiagrams() {
1234
1235                JFreeChart taskDiagram = null;
1236                JFreeChart waitingTimeDiagram = null;
1237
1238                if (!generateDiagrams)
1239                        return false;
1240
1241                String fileName = new File(outputFolderName, DIAGRAMS_FILE_NAME_PREFIX + simulationIdentifier + "_")
1242                                .getAbsolutePath();
1243
1244                String chartName = "Gantt diagram for " + GridSchedulingSimulator.SIMULATOR_NAME;
1245                String simulationTime = "Simulation time";
1246                Title subtitle = new TextTitle("created for \"" + simulationIdentifier + "\" at "
1247                                + Calendar.getInstance().getTime().toString());
1248
1249                if (configuration.creatediagrams_tasks) {
1250                        taskDiagram = getTaskDiagram(chartName, subtitle, simulationTime);
1251                        if (!saveCategoryChart(taskDiagram, fileName + "Tasks", null /* "{0}" */))
1252                                return false;
1253                }
1254
1255                if (configuration.creatediagrams_taskswaitingtime) {
1256                        waitingTimeDiagram = getWaitingTimeDiagram(chartName, subtitle, simulationTime);
1257                        if (!saveCategoryChart(waitingTimeDiagram, fileName + "Waiting_Time", null /* "Task {1} at {0}" */))
1258                                return false;
1259                }
1260
1261                return true;
1262        }
1263
1264        private JFreeChart getTaskDiagram(String chartName, Title subtitle, String simulationTime) {
1265                String tasks = "Tasks";
1266                boolean urls = false;
1267                boolean tooltip = true;
1268                boolean legend = true;
1269                JFreeChart chart = ChartFactory.createGanttChart(chartName, tasks, simulationTime,
1270                                ganttDiagramTaskSeriesCollection, legend, tooltip, urls);
1271                chart.addSubtitle(subtitle);
1272                GanttRenderer re = (GanttRenderer) chart.getCategoryPlot().getRenderer();
1273                re.setCompletePaint(Color.black);
1274                return chart;
1275        }
1276
1277        private JFreeChart getWaitingTimeDiagram(String chartName, Title subtitle, String simulationTime) {
1278                String tasks = "Tasks";
1279                boolean urls = false;
1280                boolean tooltip = true;
1281                boolean legend = true;
1282                JFreeChart chart = ChartFactory.createGanttChart(chartName, tasks, simulationTime,
1283                                ganttDiagramWaitingTimeSeriesCollection, legend, tooltip, urls);
1284                chart.addSubtitle(subtitle);
1285                chart.getPlot().setForegroundAlpha(ALPHA);
1286                GanttRenderer re = (GanttRenderer) chart.getCategoryPlot().getRenderer();
1287                re.setCompletePaint(Color.black);
1288                return chart;
1289        }
1290
1291        private boolean saveCategoryChart(JFreeChart c, String fileName, String labelFormat) {
1292                c.setNotify(false);
1293                c.setAntiAlias(true);
1294                c.setTextAntiAlias(true);
1295                c.setBorderVisible(false);
1296
1297                CategoryPlot categoryplot = (CategoryPlot) c.getPlot();
1298                categoryplot.setDomainGridlinesVisible(true);
1299
1300                if (labelFormat != null) {
1301                        CategoryItemRenderer rend = categoryplot.getRenderer();
1302                        rend.setBaseItemLabelsVisible(true);
1303                        ItemLabelPosition position = new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER);
1304                        rend.setBasePositiveItemLabelPosition(position);
1305                        NumberFormat nf = NumberFormat.getInstance();
1306                        CategoryItemLabelGenerator gen = new StandardCategoryItemLabelGenerator(labelFormat, nf);
1307                        rend.setBaseItemLabelGenerator(gen);
1308                }
1309
1310                int rows = c.getCategoryPlot().getDataset().getColumnKeys().size();
1311
1312                int height = 900;
1313                if (rows > 45) {
1314                        height = rows * 20;
1315                }
1316                int width = calculateChartWidth(c);
1317                CategoryItemRenderer rend = c.getCategoryPlot().getRenderer();
1318
1319                for (int i = 0; i < c.getCategoryPlot().getDataset().getRowKeys().size(); i++) {
1320                        Paint collor = c.getCategoryPlot().getDrawingSupplier().getNextPaint();
1321                        rend.setSeriesOutlinePaint(i, collor);
1322                        rend.setSeriesPaint(i, collor);
1323                }
1324
1325                ChartRenderingInfo info = new ChartRenderingInfo();
1326                // info.setEntityCollection(null);
1327                File f = new File(fileName + "." + ImageFormat.PNG);
1328                final String gssimSubtitle = "Created by " + GridSchedulingSimulator.SIMULATOR_NAME + " http://www.gssim.org/";
1329                c.addSubtitle(new TextTitle(gssimSubtitle));
1330                boolean encodeAlpha = false;
1331                int compression = 9;
1332                try {
1333                        ChartUtilities.saveChartAsPNG(f, c, width, height, info, encodeAlpha, compression);
1334
1335                } catch (IOException e) {
1336                        e.printStackTrace();
1337                        return false;
1338                } catch (Exception e) {
1339                        if (log.isErrorEnabled())
1340                                log.error("The png file (" + fileName
1341                                                + ")\nwill not be generated (It can be too large data size problem)", e);
1342                } catch (Throwable t) {
1343                        log.error("The png file (" + fileName + ")\nwill not be generated (It can be too large data size problem)",
1344                                        t);
1345                }
1346
1347                return true;
1348        }
1349
1350        private int calculateChartWidth(JFreeChart c) {
1351
1352                int ganttWidth = GANTT_WIDTH;
1353                int rows = c.getCategoryPlot().getDataset().getColumnKeys().size();
1354
1355                if (rows > 45) {
1356                        int height = rows * 20;
1357                        ganttWidth = Math.max((int) (height * 1.5), GANTT_WIDTH);
1358                }
1359                return ganttWidth;
1360        }
1361
1362        private static class JobIdComparator implements Comparator<JobInterface<?>> {
1363
1364                public int compare(JobInterface<?> o1, JobInterface<?> o2) {
1365                        try {
1366                                Integer o1int;
1367                                Integer o2int;
1368                                try{
1369                                        o1int = Integer.parseInt(o1.getId());
1370                                        o2int = Integer.parseInt(o2.getId());
1371                                        return o1int.compareTo(o2int);
1372                                } catch(NumberFormatException e){
1373                                        return o1.getId().compareTo(o2.getId());
1374                                }
1375
1376                        } catch (NoSuchFieldException e) {
1377                                e.printStackTrace();
1378                        }
1379                        return -1;
1380                }
1381        }
1382       
1383        private static class MapPEIdComparator implements Comparator<String> {
1384
1385                public int compare(String o1, String o2)  {
1386                        Integer o1int;
1387                        Integer o2int;
1388
1389                        o1int = Integer.parseInt(o1.substring(o1.indexOf("_")+1));
1390                        o2int = Integer.parseInt(o2.substring(o2.indexOf("_")+1));
1391                        return o1int.compareTo(o2int);
1392                }
1393        }
1394
1395}
1396
1397class ResStat{
1398       
1399       
1400        public long getStartDate() {
1401                return startDate;
1402        }
1403        public void setStartDate(long startDate) {
1404                this.startDate = startDate;
1405        }
1406        public long getEndDate() {
1407                return endDate;
1408        }
1409        public void setEndDate(long endDate) {
1410                this.endDate = endDate;
1411        }
1412        public String getTaskID() {
1413                return taskID;
1414        }
1415        public void setTaskID(String taskID) {
1416                this.taskID = taskID;
1417        }
1418
1419        public ResStat( String peName, long startDate, long endDate, String taskID) {
1420                super();
1421                this.startDate = startDate;
1422                this.endDate = endDate;
1423                this.taskID = taskID;
1424                this.peName = peName;
1425        }
1426        public String getPeName() {
1427                return peName;
1428        }
1429        public void setPeName(String peName) {
1430                this.peName = peName;
1431        }
1432        public ResStat(String peName, ResourceType resType, long startDate, long endDate, String taskID) {
1433                super();
1434                this.peName = peName;
1435                this.resType = resType;
1436                this.startDate = startDate;
1437                this.endDate = endDate;
1438                this.taskID = taskID;
1439        }
1440        String peName;
1441        ResourceType resType;
1442        long startDate;
1443        long endDate;
1444        String taskID;
1445
1446        public ResourceType getResType() {
1447                return resType;
1448        }
1449        public void setResType(ResourceType resType) {
1450                this.resType = resType;
1451        }
1452}
1453
1454enum Stats{
1455        textLoad,
1456        chartLoad,
1457        textEnergy,
1458        chartEnergy;
1459}
Note: See TracBrowser for help on using the repository browser.