Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
ntpl011_global_temperatures.C
Go to the documentation of this file.
1/// \file
2/// \ingroup tutorial_ntuple
3/// \notebook
4/// This ROOT 7 example demonstrates how to use RNTuple in combination with ROOT 6 features like RDataframe and
5/// visualizations. It ingests climate data and creates a model with fields like AverageTemperature. Then it uses
6/// RDataframe to process and filter the climate data for average temperature per city by season. Then it does the same
7/// for average temperature per city for the years between 1993-2002, and 2003-2013. Finally, the tutorial visualizes
8/// this processed data through histograms.
9///
10/// TODO(jblomer): re-enable once issues are fixed (\macro_image (rcanvas_js))
11/// \macro_code
12///
13/// \date 2021-02-26
14/// \author John Yoon
15
16// NOTE: The RNTuple classes are experimental at this point.
17// Functionality and interface are still subject to changes.
18// During ROOT setup, configure the following flags:
19// `-DCMAKE_CXX_STANDARD=17 -Droot7=ON -Dwebgui=ON`
20// When running, make sure the ROOT web-based canvas is enabled,
21// e.g., by starting "root --web=on".
22
23#include <ROOT/RDataFrame.hxx>
24#include <ROOT/RNTupleDS.hxx>
25#include <ROOT/RNTupleModel.hxx>
27#include <ROOT/RCanvas.hxx>
28#include <ROOT/RColor.hxx>
31#include <ROOT/RRawFile.hxx>
32#include <TH1D.h>
33#include <TLegend.h>
34#include <TSystem.h>
35
36#include <algorithm>
37#include <cassert>
38#include <cstdio>
39#include <fstream>
40#include <iostream>
41#include <memory>
42#include <string>
43#include <sstream>
44#include <stdexcept>
45#include <utility>
46#include <chrono>
47
48using Clock = std::chrono::high_resolution_clock;
49using RRawFile = ROOT::Internal::RRawFile;
50using namespace ROOT::Experimental;
51
52// Helper function to handle histogram pointer ownership.
53std::shared_ptr<TH1D> GetDrawableHist(ROOT::RDF::RResultPtr<TH1D> &h)
54{
55 auto result = std::shared_ptr<TH1D>(static_cast<TH1D *>(h.GetPtr()->Clone()));
56 result->SetDirectory(nullptr);
57 return result;
58}
59
60// Climate data is downloadable at the following URL:
61// https://www.kaggle.com/berkeleyearth/climate-change-earth-surface-temperature-data
62// The original data set is from http://berkeleyearth.org/archive/data/
63// License CC BY-NC-SA 4.0
64constexpr const char *kRawDataUrl = "http://root.cern./files/tutorials/GlobalLandTemperaturesByCity.csv";
65constexpr const char *kNTupleFileName = "GlobalLandTemperaturesByCity.root";
66
67void Ingest()
68{
69 int nRecords = 0;
70 int nSkipped = 0;
71 std::cout << "Converting " << kRawDataUrl << " to " << kNTupleFileName << std::endl;
72
73 auto t1 = Clock::now();
74
75 // Create a unique pointer to an empty data model.
76 auto model = RNTupleModel::Create();
77 // To define the data model, create fields with a given C++ type and name. Fields are roughly TTree branches.
78 // MakeField returns a shared pointer to a memory location to fill the ntuple with data.
79 auto fieldYear = model->MakeField<std::uint32_t>("Year");
80 auto fieldMonth = model->MakeField<std::uint32_t>("Month");
81 auto fieldDay = model->MakeField<std::uint32_t>("Day");
82 auto fieldAvgTemp = model->MakeField<float>("AverageTemperature");
83 auto fieldTempUncrty = model->MakeField<float>("AverageTemperatureUncertainty");
84 auto fieldCity = model->MakeField<std::string>("City");
85 auto fieldCountry = model->MakeField<std::string>("Country");
86 auto fieldLat = model->MakeField<float>("Latitude");
87 auto fieldLong = model->MakeField<float>("Longitude");
88
89 // Hand-over the data model to a newly created ntuple of name "globalTempData", stored in kNTupleFileName.
90 // In return, get a unique pointer to a fillable ntuple (first compress the file).
91 auto ntuple = RNTupleWriter::Recreate(std::move(model), "GlobalTempData", kNTupleFileName);
92
93 // Download data in 4MB blocks
94 RRawFile::ROptions options;
95 options.fBlockSize = 4'000'000;
96
97 auto file = RRawFile::Create(kRawDataUrl, options);
98 std::string record;
99 constexpr int kMaxCharsPerLine = 128;
100 while (file->Readln(record)) {
101 if (record.length() >= kMaxCharsPerLine)
102 throw std::runtime_error("record too long: " + record);
103
104 // Parse lines of the form:
105 // 1743-11-01,6.068,1.7369999999999999,Ã…rhus,Denmark,57.05N,10.33E
106 // and skip records with empty fields.
107 std::replace(record.begin(), record.end(), ',', ' ');
108 char country[kMaxCharsPerLine];
109 char city[kMaxCharsPerLine];
110 int nFields =
111 sscanf(record.c_str(), "%u-%u-%u %f %f %s %s %fN %fE", fieldYear.get(), fieldMonth.get(), fieldDay.get(),
112 fieldAvgTemp.get(), fieldTempUncrty.get(), country, city, fieldLat.get(), fieldLong.get());
113 if (nFields != 9) {
114 nSkipped++;
115 continue;
116 }
117 *fieldCountry = country;
118 *fieldCity = city;
119
120 ntuple->Fill();
121
122 if (++nRecords % 1000000 == 0)
123 std::cout << " ... converted " << nRecords << " records" << std::endl;
124 }
125
126 // Display the total time to process the data.
127 std::cout << nSkipped << " records skipped" << std::endl;
128 std::cout << nRecords << " records processed" << std::endl;
129
130 auto t2 = Clock::now();
131 std::cout << std::endl
132 << "Processing Time: " << std::chrono::duration_cast<std::chrono::seconds>(t2 - t1).count() << " seconds\n"
133 << std::endl;
134}
135
136// Every data result that we want to get is declared first, and it is only upon their declaration that
137// they are actually used. This stems from motivations relating to efficiency and optimization.
138void Analyze()
139{
140 // Create a RDataframe by wrapping around NTuple.
141 ROOT::RDataFrame df("GlobalTempData", kNTupleFileName);
142 df.Display()->Print();
143
144 // Declare the minimum and maximum temperature from the dataset.
145 auto min_value = df.Min("AverageTemperature");
146 auto max_value = df.Max("AverageTemperature");
147
148 // Functions to filter by each season from date formatted "1944-12-01."
149 auto fnWinter = [](int month) { return month == 12 || month == 1 || month == 2; };
150 auto fnSpring = [](int month) { return month == 3 || month == 4 || month == 5; };
151 auto fnSummer = [](int month) { return month == 6 || month == 7 || month == 8; };
152 auto fnFall = [](int month) { return month == 9 || month == 10 || month == 11; };
153
154 // Create a RDataFrame per season.
155 auto dfWinter = df.Filter(fnWinter, {"Month"});
156 auto dfSpring = df.Filter(fnSpring, {"Month"});
157 auto dfSummer = df.Filter(fnSummer, {"Month"});
158 auto dfFall = df.Filter(fnFall, {"Month"});
159
160 // Get the count for each season.
161 auto winterCount = dfWinter.Count();
162 auto springCount = dfSpring.Count();
163 auto summerCount = dfSummer.Count();
164 auto fallCount = dfFall.Count();
165
166 // Functions to filter for the time period between 2003-2013, and 1993-2002.
167 auto fn1993_to_2002 = [](int year) { return year >= 1993 && year <= 2002; };
168 auto fn2003_to_2013 = [](int year) { return year >= 2003 && year <= 2013; };
169
170 // Create a RDataFrame for decades 1993_to_2002 & 2003_to_2013.
171 auto df1993_to_2002 = df.Filter(fn1993_to_2002, {"Year"});
172 auto df2003_to_2013 = df.Filter(fn2003_to_2013, {"Year"});
173
174 // Get the count for each decade.
175 auto decade_1993_to_2002_Count = *df1993_to_2002.Count();
176 auto decade_2003_to_2013_Count = *df2003_to_2013.Count();
177
178 // Configure histograms for each season.
179 auto fallHistResultPtr =
180 dfFall.Histo1D({"Fall Average Temp", "Average Temperature by Season", 100, -40, 40}, "AverageTemperature");
181 auto winterHistResultPtr =
182 dfWinter.Histo1D({"Winter Average Temp", "Average Temperature by Season", 100, -40, 40}, "AverageTemperature");
183 auto springHistResultPtr =
184 dfSpring.Histo1D({"Spring Average Temp", "Average Temperature by Season", 100, -40, 40}, "AverageTemperature");
185 auto summerHistResultPtr =
186 dfSummer.Histo1D({"Summer Average Temp", "Average Temperature by Season", 100, -40, 40}, "AverageTemperature");
187
188 // Configure histograms for each decade.
189 auto hist_1993_to_2002_ResultPtr = df1993_to_2002.Histo1D(
190 {"1993_to_2002 Average Temp", "Average Temperature: 1993_to_2002 vs. 2003_to_2013", 100, -40, 40},
191 "AverageTemperature");
192 auto hist_2003_to_2013_ResultPtr = df2003_to_2013.Histo1D(
193 {"2003_to_2013 Average Temp", "Average Temperature: 1993_to_2002 vs. 2003_to_2013", 100, -40, 40},
194 "AverageTemperature");
195
196 //____________________________________________________________________________________
197
198 // Display the minimum and maximum temperature values.
199 std::cout << std::endl << "The Minimum temperature is: " << *min_value << std::endl;
200 std::cout << "The Maximum temperature is: " << *max_value << std::endl;
201
202 // Display the count for each season.
203 std::cout << std::endl << "The count for Winter: " << *winterCount << std::endl;
204 std::cout << "The count for Spring: " << *springCount << std::endl;
205 std::cout << "The count for Summer: " << *summerCount << std::endl;
206 std::cout << "The count for Fall: " << *fallCount << std::endl;
207
208 // Display the count for each decade.
209 std::cout << std::endl << "The count for 1993_to_2002: " << decade_1993_to_2002_Count << std::endl;
210 std::cout << "The count for 2003_to_2013: " << decade_2003_to_2013_Count << std::endl;
211
212 // Transform histogram in order to address ROOT 7 v 6 version compatibility
213 auto fallHist = GetDrawableHist(fallHistResultPtr);
214 auto winterHist = GetDrawableHist(winterHistResultPtr);
215 auto springHist = GetDrawableHist(springHistResultPtr);
216 auto summerHist = GetDrawableHist(summerHistResultPtr);
217
218 // Set an orange histogram for fall.
219 fallHist->SetLineColor(kOrange);
220 fallHist->SetLineWidth(6);
221 // Set a blue histogram for winter.
222 winterHist->SetLineColor(kBlue);
223 winterHist->SetLineWidth(6);
224 // Set a green histogram for spring.
225 springHist->SetLineColor(kGreen);
226 springHist->SetLineWidth(6);
227 // Set a red histogram for summer.
228 summerHist->SetLineColor(kRed);
229 summerHist->SetLineWidth(6);
230
231 // Transform histogram in order to address ROOT 7 v 6 version compatibility
232 auto hist_1993_to_2002 = GetDrawableHist(hist_1993_to_2002_ResultPtr);
233 auto hist_2003_to_2013 = GetDrawableHist(hist_2003_to_2013_ResultPtr);
234
235 // Set a violet histogram for 1993_to_2002.
236 hist_1993_to_2002->SetLineColor(kViolet);
237 hist_1993_to_2002->SetLineWidth(6);
238 // Set a spring-green histogram for 2003_to_2013.
239 hist_2003_to_2013->SetLineColor(kSpring);
240 hist_2003_to_2013->SetLineWidth(6);
241
242 // Create a canvas to display histograms for average temperature by season.
243 auto canvas = RCanvas::Create("Average Temperature by Season");
244 canvas->Draw<TObjectDrawable>(fallHist, "L");
245 canvas->Draw<TObjectDrawable>(winterHist, "L");
246 canvas->Draw<TObjectDrawable>(springHist, "L");
247 canvas->Draw<TObjectDrawable>(summerHist, "L");
248
249 // Create a legend for the seasons canvas.
250 auto legend = std::make_shared<TLegend>(0.15, 0.65, 0.53, 0.85);
251 legend->AddEntry(fallHist.get(), "fall", "l");
252 legend->AddEntry(winterHist.get(), "winter", "l");
253 legend->AddEntry(springHist.get(), "spring", "l");
254 legend->AddEntry(summerHist.get(), "summer", "l");
255 canvas->Draw<TObjectDrawable>(legend, "L");
256 canvas->Show();
257
258 // Create a canvas to display histograms for average temperature for 1993_to_2002 & 2003_to_2013.
259 auto canvas2 = RCanvas::Create("Average Temperature: 1993_to_2002 vs. 2003_to_2013");
260 canvas2->Draw<TObjectDrawable>(hist_1993_to_2002, "L");
261 canvas2->Draw<TObjectDrawable>(hist_2003_to_2013, "L");
262
263 // Create a legend for the two decades canvas.
264 auto legend2 = std::make_shared<TLegend>(0.1, 0.7, 0.48, 0.9);
265 legend2->AddEntry(hist_1993_to_2002.get(), "1993_to_2002", "l");
266 legend2->AddEntry(hist_2003_to_2013.get(), "2003_to_2013", "l");
267 canvas2->Draw<TObjectDrawable>(legend2, "L");
268 canvas2->Show();
269}
270
271void ntpl011_global_temperatures()
272{
273 // if NOT zero (the file does NOT already exist), then Ingest
274 if (gSystem->AccessPathName(kNTupleFileName) != 0) {
275 Ingest();
276 }
277 Analyze();
278}
#define h(i)
Definition RSha256.hxx:106
@ kRed
Definition Rtypes.h:66
@ kOrange
Definition Rtypes.h:67
@ kGreen
Definition Rtypes.h:66
@ kBlue
Definition Rtypes.h:66
@ kViolet
Definition Rtypes.h:67
@ kSpring
Definition Rtypes.h:67
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t result
R__EXTERN TSystem * gSystem
Definition TSystem.h:561
Provides v7 drawing facilities for TObject types (TGraph, TH1, TH2, etc).
The RRawFile provides read-only access to local and remote files.
Definition RRawFile.hxx:43
Smart pointer for the return type of actions.
ROOT's RDataFrame offers a modern, high-level interface for analysis of data stored in TTree ,...
1-D histogram with a double per channel (see TH1 documentation)
Definition TH1.h:671
virtual Bool_t AccessPathName(const char *path, EAccessMode mode=kFileExists)
Returns FALSE if one can access a file using the specified access mode.
Definition TSystem.cxx:1296
On construction, an ROptions parameter can customize the RRawFile behavior.
Definition RRawFile.hxx:49
size_t fBlockSize
Read at least fBlockSize bytes at a time. A value of zero turns off I/O buffering.
Definition RRawFile.hxx:54
auto * t1
Definition textangle.C:20