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