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