In this chapter we introduce commands to access databases containing up-to-date information from many different fields such as: astronomy, chemistry, economy, genetics, geography, physics and many more. These commands can be part of Mathematica-based programs. In later chapters we will make extensive use of some them.
Mathematica has functions to access databases from many different fields such as:
Physics and Chemistry: ElementData, ChemicalData, IsotopeData, ParticleData ...
Earth Sciences: WeatherData, GeodesyData, GeoDistance ...
Astronomy: StarData , PlanetData ...
Life Sciences and Medicine: GenomeData, GenomeLookup, ProteinData ...
Economics and Finance: FinancialData, CountryData ...
Mathematics: FiniteGroupData, GraphData, KnotData, LatticeData, PolyhedronData ...
Linguistics: DictionaryLookup, WordData, ExampleData ...
Engineering: AircraftData, BridgeData, NuclearReactorData ...
People and History: PersonData, SocialMediaData, MovieData, Historical PeriodData ...
Geography: GeoGraphics, GeoListPlot ...
The number of fields covered by Mathematica keeps on growing with each new release of the program. The big advantage of these functions is that they import the data – internally known as computable data or collections – in a format that makes their manipulation easy. When using them, Mathematica will connect to a server at Wolfram Research which in turn will access a specialized server containing the relevant data. There are three different types of data collections: (i) Pre-computed: most of the mathematical data is precomputed in a Wolfram server: e.g., GraphData, KnotData, LatticeData, PolyhedronData; (ii) Aggregated from publicly available sources: e.g., AstronomicalData, CityData, CountryData, ChemicalData, ElementData, IsotopeData, ParticleData, WordData; Direct connection to web services-based provider: e.g., FinancialData, WeatherData. The execution time may vary depending on the speed of your Internet connection and that of the Wolfram Research server itself.
In many cases, the word “Data” is included in this type of functions. You can use ?*Data* to explore some of them (output not shown).
?*Data*
One of the functions included in the data collections is FinancialData for manipulating finance-related data. This command is complemented by some others that we will cover in Chapter 11. For example: we can get the euro/dollar exchange rate at the time of the query.
FinancialData ["EUR /USD"]
1.1087
If you get an error message when evaluating the previous expression it may be due to problems with your firewall or proxy configuration for accessing the Internet. Check your Mathematica settings in: Edit ► Preferences ► Proxy settings. If the issue is proxy-related, access the help system for information about how to troubleshoot it: tutorial/TroubleshootingInternetConnectivity.
Mathematica has an extensive selection of scientific and technical formulas. Use FormulaLookup to find their precise names. For instance: If you need the formula for relativistic kinetic energy, you can type:
FormulaLookup ["Relativistic Kinetic Energy"]
{KineticEnergyRelativistic }
Now use FormulaData data to obtain the actual formula:
FormulaData ["KineticEnergyRelativistic"]
Of course, you can use free form input as usual: typing “=” at the beginning of an input cell followed by the relevant words in plain English.
This alternative way can give us the information that we are looking for using computable data. As a matter of fact, it will not only display the results but also the appropriate Mathematica input function. Nevertheless, in this chapter we will type the computable function directly, the best approach if we want to write programs. However, we recommend the reader to take advantage of the free-form input and use it as the starting point for more sophisticated queries.
The following pages contain illustrations about the use of some the functions for computable data. The examples shown may be more difficult than the average ones included in this book. If that’s the case, you may want to use them as templates and make the necessary modifications to suit your needs. As usual, we strongly recommend seeking further information about the functions in the help files to find out more about all of their potential uses.
In general, computable data functions contain a list of properties related to the entity (Entity) to which they refer. Typing Function[“Properties”] will tell us all the available properties of Function. Alternatively, we can always go to the help page for the function.
For example, the properties available for WordData are:
WordData ["Properties"]
{AmericanSpelling, Antonyms, BaseAdjective, BaseForm, BaseNoun,
BritishSpelling, BroaderTerms, CausesTerms, CompositeTerms, ConceptWeight,
ConsequencesTerms, Definitions, DerivedAdjectives, DerivedAdverbs,
EntailedTerms, Examples, GeographicDomain, Hyphenation, InflectedForms,
MaterialTerms, MorphologicalDerivatives, MorphologicalSource,
NarrowerTerms, PartsOfSpeech, PartTerms, PhoneticForm, PorterStem,
SentenceFrames, SimilarAdjectives, SimilarVerbs, SubsetTerms,
SupersetTerms, Synonyms, UsageField, UsageType, WholeTerms, WordNetID}
We can ask for specific word properties using the command: WordData["word", "property"]:
WordData ["confused", "SimilarAdjectives"]
{{confused, Adjective, Dazzled}→
{addlebrained, addled, addlepated, befogged, befuddled, clouded,
dazed, dazzled, muddled, muddleheaded, muzzy, puddingheaded,
punch-drunk, silly, slaphappy, spaced -out, stunned, stupefied,
stupid, trancelike, woolly, woolly-headed, wooly, wooly -minded },
{confused, Adjective, Disjointed }→{incoherent},
{confused, Adjective, Broken }→{disorganised, disorganized},
{confused, Adjective, Disoriented }→{unoriented},
{confused, Adjective, Mazed }→{perplexed}}
In the next example we use DictionaryLookup to search for English (other languages are also available) words starting with “sh” and ending in “y”:
DictionaryLookup [{"English", "sh" ~~ __ ~~ "y"}]
{shabbily, shabby, shadily, shadowy, shady, shaggy, shakily,
shaky, shallowly, shamefacedly, shamefully, shamelessly, shandy,
shanty, shapelessly, shapely, sharply, shatteringly, shay, sheeny,
sheepishly, sherry, shiftily, shiftlessly, shifty, shimmery,
shimmy, shinny, shiny, shirty, shiveringly, shivery, shockingly,
shoddily, shoddy, shortly, shortsightedly, shorty, showery, showily,
showy, shrewdly, shrilly, shrinkingly, shrubbery, shrubby, shyly}
SpokenString [expr] transcribes the indicated expression:
transcribe = SpokenString[Sqrt[x/(y + z)]]
square root of the quantity x over the quantity y plus z
We can create a button that when pressed will return a spoken representation of the argument:
Button ["Press", Speak [transcribe]]
Next we are going to obtain the phonetic transcription (in American English) of the previous expression. We use SpokenString to split the phrase into words and the property "PhoneticForm", from WordData, to get the phonetic transcription of each word. Given that the output is a list containing the words’ phonetic transcriptions, we apply Row[list, “ ”] to join the elements substituting the commas with blank spaces.
Row[WordData [#, "PhoneticForm"] & /@ StringSplit[transcribe], " "]
In general, any computable data function is of the form: Function [“name or Entity”, “property”], or Function [“name” or “Entity”, {“property”, ...} ] where Entity is an entity identified by its name: Country, Element, Isotope ... and property is information related to such entity.
To see all the properties available for a specific function we can access the documentation or type:
CityData ["Properties"]
{AlternateNames, Coordinates, Country, Elevation,
FullName, Latitude, LocationLink, Longitude, Name,
Population, Region, RegionName, StandardName, TimeZone}
If you type the entity, in this case “Salamanca”, Mathematica will return all the cities in the world with that name:
CityData ["Salamanca"]
By hovering the mouse over the list elements, you will see the details for each of the cities. If you prefer to see them explicitly, just type the following:
salamanca =
SemanticInterpretation ["Salamanca",
Entity [First [salamanca ["City", _], AmbiguityFunction → All]
Take[First[salamanca], 6] // InputForm
{Entity["City", {"Salamanca", "Coquimbo", "Chile"}],
Entity["City", {"Salamanca", "Guanajuato", "Mexico"}],
Entity["City", {"Salamanca", "Salamanca", "Spain"}],
Entity["City", {"Salamanca", "NewYork", "UnitedStates"}],
Entity["City", {"Salamanca", "NegrosOccidental", "Philippines"}],
Entity["City", {"Salamanca", "Colon", "Panama"}]}
If we intend to refer to a particular one, we need to be more precise and tell Mathematica exactly what we want (if we let the program select the city for us it may not make the right choice). For example: if we’d like to know the population of the Spanish city of Salamanca, we can use Entity with the output returned from the previous command.
CityData [Entity ["City", {"Salamanca", "Salamanca", "Spain" }], "Population"]
159 754 people
Alternatively we can use Interpreter (this function can be used any time there is ambiguity risk).
Interpreter ["City"]["Salamanca, Spain"]
Copy the output and paste it below:
159 754 people
Notice that the previous output displays the units explicitly, in this case people. This is the default behavior since Mathematica 10. To see the output without units use QuantityMagnitude. You can also type the entity as follows, a more convenient way if you are writing a program.
QuantityMagnitude[CityData [
Entity ["City", {"Salamanca", "Salamanca", "Spain" }] , "Population"]]
159 754
Another way is setting the system options as follows:
SetSystemOptions["DataOptions" → "ReturnQuantities" → False];
12 458 000
After executing the previous function, the units won’t be displayed for the rest of the Mathematica session. This can be useful if you have notebooks created with versions of the program prior to Version 10.
System options specify parameters relevant to the internal operations of the program. If we make changes to those options, we should always reset the parameters as soon as we are done with our calculations to avoid potential problems.
In this case we can re-enable the display of units by setting the value of the system option to true again.
SetSystemOptions["DataOptions" → "ReturnQuantities" → True];
8 491 079 people
If you wish to know all the information (properties) of a given entity of a computable data function (DF) you can use the syntax:
Transpose[{DF[“Properties”], DF[entities, #]& /@ DF[“Properties”]}]
In this case we find all the information available in CityData for the city of Salamanca, Salamanca province, Spain: {"Salamanca","Salamanca","Spain"}.
Transpose[{CityData["Properties"],
CityData [Entity ["City", {"Salamanca", "Salamanca", "Spain" }], #] & /@
CityData["Properties"]}]
{{AlternateNames, {Salamanque}}, {Coordinates, {40.97, -5.67}},
{Country, }, {Elevation, 818 m},
{FullName, Salamanca, Salamanca, Spain}, {Latitude, 40.97°},
{LocationLink, http://maps.google.com/maps?q=+40.97,-5.67&z=12&t=h},
{Longitude, −5.67°}, {Name, Salamanca}, {Population, 159 754 people },
{Region, Salamanca}, {RegionName, Salamanca},
{StandardName, {Salamanca, Salamanca, Spain}}, {TimeZone, 1 h }}
If in the previous output we select “http://maps.google.com/...” and press <F1> we will see the location of Salamanca in GoogleMaps.
Most of the computable functions establish groupings classes (entities that share some common characteristics) as displayed in the example below. We add Shallow to show only the first few lines of the result. Remove it to see the complete output.
StarData["Classes"] // Shallow
The following function displays a table with the properties and classes available for the specified collection:
DataTable[fun _Symbol] := Module[{data},
data = {
{Style [fun, "Section",
FontFamily→ "Lucida Grande", FontSize → 14], SpanFromLeft},
{"", "Length", "Examples" },
{"Entities", Length [fun []], Append[RandomChoice[fun[], 2], "…"]},
{"Properties", Length [fun ["Properties"]],
Append [RandomChoice [fun ["Properties"], 2], "…"]},
{"Classes", Length [fun
Append [RandomChoice [fun ["Classes"], 2], " …"]}
};
Grid[data, Frame → All]]
Here’s the function applied to CountryData:
DataTable[CountryData]
Very often, when starting a new section, we execute this command to remove functions that we may have previously defined to avoid potential name conflicts when defining new ones.
Clear["Global` *"]
The latest Mathematica version contains several computable functions for astronomical calculations as we will see in Chapter 8. Until Mathematica 9 the only available function was: AstronomicalData (still available) but since Mathematica 10 this function has been replaced by others containing new functionality: PlanetData , StarData ....
The curve describing the sun and the visible planets in the sky every day of the year always observed at the same location and time of the day is called analemma.
A solar analemma can be obtained with a camera and patience, taking pictures of the horizon every day or almost every day of the year from the same position, with the same exposure and at the same solar time. The result will be a composition similar to the one below. It shows an analemma taken by Jack Fishburn between 1998-1999 from Bell Laboratories in Murray Hill, New Jersey:
WikipediaData["Analemma", "ImageList"][[3]]
You can also make analemmas for other celestial objects such as Venus or Mercury.
With less patience and without having to wait for a year, we can simulate an analemma with Mathematica from our own computer.
We need to define the location (latitude and longitude).
SunPosition returns the sun position from our position (azimuth and latitude) at 9:00 AM in GMT (choosing TimeZone→0) on January 1, 2016.
SunPosition[salamanca, DateObject [{2016, 1, 1, 9}, TimeZone → 0]]
{132.67°, 9.91°}
We apply the same function to get the position every 5 days, at the same time, to complete a year:
Graphics[{Orange, PointSize[Large],
Point@Map[QuantityMagnitude, SunPosition[salamanca,
DateRange[DateObject[{2016, 1, 1, 9, 0}, TimeZone → 0],
DateObject[{2016, 12, 31, 9, 0}, TimeZone → 0], 5]][
"Values"], {2}]}, Frame → True]
The IsotopeData and ParticleData functions deal with nuclear and particle physics applications. We will make extensive use of them in Chapter 9.
IsotopeData["isotope", "property"] returns the value of the specified property for a given isotope.
You can use the name of an isotope (i.e. "Uranium235") or refer to it as {Z, A} with Z being its atomic number and A its atomic mass (i.e. instead of "Uranium235" we can write {92, 235}).
Clear ["Global` *"]
IsotopeData ["Properties"] // Shallow
{AtomicMass, AtomicNumber, BindingEnergy,
BranchingRatios, DaughterNuclides, DecayEnergies, DecayModes,
DecayModeSymbols, DecayProducts, ExcitedStateEnergies, ≪23≪ }
The next example shows the properties of Iodine–131.
["Iodine131", #] & /@
{"FullSymbol", "AtomicMass", "BranchingRatios", "DecayModes",
"DaughterNuclides", "HalfLife", "IsotopeAbundance"}
The output tells us that this isotope, whose complete symbol is
Mathematica has a group of functions to access data related to engineering structures.
For example, to explore the properties of a bridge:
In the command below we use NuclearReactorData to find out the number of nuclear reactors under construction per country (notice the use of the free-form input).
BarChart[#[[All, 2]], ChartLabels → #[[All, 1]],
BarOrigin → Left, ImageSize → Medium] & @
Tally@Flatten @NuclearReactorData [
, "Countries"]
With ElementData and ChemicalData we can access a wide variety of information about chemical elements and compounds.
Both functions use the following color scheme when representing atoms and molecules:
Clear ColorData["Global`*"]
["Atoms", "Panel"]
If you click on an element symbol, you will see the color code assigned by the function.
Let’s take a look at the properties available in ElementData:
ElementData["Properties"] // Shallow
{Abbreviation, AdiabaticIndex, AllotropeNames,
AllotropicMultiplicities, AlternateNames, AlternateStandardNames,
AtomicMass, AtomicNumber, AtomicRadius, Block, ≪75≫}
ElementData["element", "property"] displays the requested property information for a given element.
The next function displays the crystalline structure of an element in its solid phase:
We choose several carbon properties and present them in a table format using Grid.
carbonproperties=
{"AbsoluteBoilingPoint", "AbsoluteMeltingPoint", "AtomicRadius",
"AtomicWeight", "Density", "FusionHeat", "IsotopeAbundances",
"LatticeAngles", "LatticeConstants", "MagneticType", "MolarVolume",
"Name", "Phase", "QuantumNumbers", "Resistivity", "SolarAbundance",
"SpecificHeat", "ThermalConductivity", "ThermalExpansion"};
Grid[{#, ElementData["C", #]} & /@ carbonproperties, Frame → True,
Alignment→{Left}, Background →{None, {{LightRed, Pink}}}]
We can know the units, in the international system (SI), of the corresponding property.
units = {#, ElementData["C", #, "UnitsNotation" ]} & /@ carbonproperties
{{AbsoluteBoilingPoint, K}, {AbsoluteMeltingPoint, K},
{AtomicRadius, pm}, {AtomicWeight, Missing[NotAvailable]},
{Density, kg/m3}, {FusionHeat, Missing[NotAvailable]},
{IsotopeAbundances, Missing[NotApplicable]},
{LatticeAngles, rad}, {LatticeConstants, pm},
{MagneticType, Missing[NotApplicable]}, {MolarVolume, m3/mol},
{Name, Missing[NotApplicable]}, {Phase, Missing[NotApplicable]},
{QuantumNumbers, Missing[NotApplicable]}, {Resistivity, Ωm},
{SolarAbundance, Missing[NotAvailable]}, {SpecificHeat, J/(kg K)},
{ThermalConductivity, W/(mK)}, {ThermalExpansion, 1/K}}
Before showing them, we eliminate non-dimensional properties or those without SI units. In such cases the output generated indicates ElementData or Missing (you can check it by removing the “;” from the previous command). To perform the operation we use DeleteCases in combination with “_ElementData” and “_Missing.
DeleteCases[DeleteCases[units, {_, _ElementData}], {_, _Missing}]
{{AbsoluteBoilingPoint, K}, {AbsoluteMeltingPoint, K}, {AtomicRadius, pm},
{Density, kg/m3}, {LatticeAngles, rad}, {LatticeConstants, pm},
{MolarVolume, m3/mol}, {Resistivity, Ωm}, {SpecificHeat, J/(kg K)},
{ThermalConductivity, W/(mK)}, {ThermalExpansion, 1/K}}
The following command tells us the abundance (as a fraction of the mass) of the different elements in the human body.
humanabundance =
Table [{QuantityMagnitude[ElementData[z, "HumanAbundance"]],
ElementData[z]}, {z, 92}];
We keep those whose presence in the body is greater than 0.001. We order them by comparing the first element of each sublist using Sort and a pure function.
Sort[Cases[humanabundance, {x_, y_} /; x > 0.001], #1[[1]] > #2[[1]] &]
ChemicalData ["compound", "property"] shows the information specified in “property” for a given compound.
In the example that follows we show the caffeine molecular plot. Once the command has been executed we can move the plot with the mouse to visualize the molecule from different perspectives.
ChemicalData["Caffeine", "MoleculePlot"]
We can compare two biomolecules based on their chemical formulas and molecular plots:
Grid [Outer [ChemicalData, {"Glycine", "L -Tyrosine"},
{"Name", "ColorStructureDiagram", "MoleculePlot"}]]
Given a compound, the following function returns its name, structure diagram, formula, molecular weight, dielectric constant, density and boiling point:
ChemicalTable1[chemicals_List] :=
Grid[Transpose[(Table[ChemicalData[#, property],
{property, {"Name", "ColorStructureDiagram", "FormulaDisplay",
"MolecularWeight", "DielectricConstant", "DensityGramsPerCC",
"BoilingPoint"}}] & /@ chemicals)], Frame → All]
ChemicalTable1[{"Cyclohexanol", "Acetone"}]
The function below is similar to the previous one in terms of its contents but the information displayed is more elaborated. You can use it as a template.
ChemicalTable[chemicals_List] := Module[{labels, style, data, img},
labels = {"Name", "Color Structure Diagram", "Formula",
"Molecular Weight", "Density (g cm-3)", "Dielectric Constant",
"Boiling Point (°C)", "Flash Point (°C)", "NFPA Lavel"};
style := Style[#, FontFamily → "Helvetica", FontWeight → Bold] &;
data = (Table[ChemicalData[#, property],
{property, {"Name", "ColorStructureDiagram", "FormulaDisplay",
"MolecularWeight", "DensityGramsPerCC", "DielectricConstant",
"BoilingPoint", "FlashPoint", "NFPALabel"}}] & /@ chemicals);
img = Text[Style[Grid[Transpose[Join[{style /@ labels}, data]],
Frame → All,
Background → {LightYellow, {{{GrayLevel[0.9], White}}}},
Alignment → {{Left, {Center}}, Center}],
FontFamily → "Helvetica", Bold, 13]
];
img /. {(ImageSize → _?NumericQ) → (ImageSize → 110),
(ImageSize → x_List) → (ImageSize → 1.2*x)}
]
This function can be applied directly to a list of arbitrary length. In this case we use it with two compounds.
ChemicalTable[{"Cyclohexanol", "Acetone"}]
The following examples refer to typical functions applicable to genetic and protein data related to humans.
GenomeLookup shows the chromosomes in which a specified DNA sequence appears along with its position inside of them.
Clear["Global`*"] (*Clears values and
definitions for all the previously defined variables*)
GenomeLookup["AATTTCCGTTAAAT"]
{{{Chromosome2, 1}, {213 319 362, 213 319 375}},
{{Chromosome3, -1}, {83 249 225, 83 249 238}},
{{Chromosome7, -1}, {78 235 739, 78 235 752}},
{{Chromosome9, -1}, {5 746 733, 5 746 746}},
{{Chromosome11, 1}, {41 489 916, 41 489 929}},
{{Chromosome11, -1}, {124 909 525, 124 909 538}},
{{Chromosome22, -1}, {11 132 978, 11 132 991}},
{{ChromosomeX, 1}, {144 568 117, 144 568 130}}}
GenomeData["gene", "property"] gives the DNA sequence for a specified gene on the human genome. With "property" we can specify a characteristic of the chosen gene. In this example we show the biological processes where the gene “ACAA2” plays a role.
GenomeData["ACAA2", "BiologicalProcesses"]
{CholesterolBiosyntheticProcess, FattyAcidMetabolicProcess,
LipidMetabolicProcess, MetabolicProcess}
ProteinData["protein"] returns the amino acids of a given protein. In this case we display the sequence of the protein A2M. We use Short to avoid displaying the complete output.
ProteinData["A2M"] // Short
MGKNKLLHPSLVLLLLVLLPTDASVSGKPQYMVL …RDLKPAIVKVYDYYETDEFAIAEYNAPCSKDLGNA
ProteinData["protein", "property"] gives us the option to choose the property of the protein that we want to know about. As an illustration, to know the graphical representation of the A2M protein, we can use “MoleculePlot” (this property is not yet available for all proteins at the time of writing).
ProteinData["A2M", "MoleculePlot"]
The following functions are considerably more complicated (some of them have been adapted from examples and documentation provided by Wolfram Research). You may find them useful as they are or you could use them as templates and make the necessary adjustments to suit your needs.
This first example represents each atom of the A2M protein. The atoms are scaled. Their atomic radii have been obtained from ElementData and their colors follow the scheme in ColorData, as previously mentioned.
With[{p = "A2M", cr = Dispatch@ColorData["Atoms", "ColorRules"]},
Graphics3D[MapThread[{#2 /. cr, Sphere[#1,
QuantityMagnitude[ElementData[#2, "VanDerWaalsRadius"]]]} &,
{QuantityMagnitude[ProteinData[p, "AtomPositions"]],
Flatten[ProteinData[p, "AtomTypes"]]}], Boxed → False]]
The function below identifies the chromosomes and the position inside of them where a DNA sequence is located.
FindSequence[sequence_] :=
chrpos =
SortBy[
Module[{chr = #, len, scale = N[GenomeData[#, "SequenceLength"] /
GenomeData["Chromosome1", "SequenceLength"]],
rls},
rls = Flatten[{#[[1, 1, 1]] → (#[[All, 2, 1]] *scale/len) & /@
SplitBy[Select[GenomeLookup[sequence],
#[[1, 2]] .1 &], #[[1, 1]] &], _ → {}}];
len = GenomeData[chr, "SequenceLength"];
{chr,
Extract[GenomeData[chr, "GBandScaledPositions"],
Position[GenomeData[chr, "GBandStainingCodes"],
"acen", 1, 1]][[1, 1]] *scale, scale,
GenomeData[#, "AlternateStandardNames"][[1]],
GenomeData[chr, "AlternateStandardNames"][[2]], # /. rls}] & /@
Most@GenomeData["Chromosomes"], #[[5]] &];
Here we use the previously defined function (FindSequence[]) to find, for a given sequence, the chromosomes and the position in which they appear.
FindSequence["AACCTTGGGAAATT"] // Shallow
{{Chromosome1, 0.471457, 1., 1, 1, {≪3≫}},
{Chromosome2, 0.362134, 0.982614, 2, 2, {≪5≫}},
{Chromosome3, 0.354132, 0.806884, 3, 3, {≪3≫}},
{Chromosome4, 0.199253, 0.773603, 4, 4, {≪8≫}},
{Chromosome5, 0.166101, 0.731479, 5, 5, {≪3≫}},
{Chromosome6, 0.23412, 0.691204, 6, 6, {≪1≫}},
{Chromosome7, 0.227125, 0.642352, 7, 7, {≪3≫}},
{Chromosome8, 0.168017, 0.591608, 8, 8, {≪1≫}},
{Chromosome9, 0.180048, 0.567334, 9, 9, {}},
{Chromosome10, 0.163645, 0.547522, 10, 10, {≪1≫}}, ≪14≫}
The next function is equivalent to the last one but its output is shown as a graphical representation.
PlotSequence :=
Graphics@
MapIndexed[
With[{i = #2[[1]]},
{White, EdgeForm[{Black, Thickness[0.005]}], Rectangle[
{0, i/15.}, {#[[2]], i/15. + 1/30.}, RoundingRadius → 0.5/30],
Rectangle[{#[[2]], i/15.}, {#[[3]], i/15. + 1/30.},
RoundingRadius → 0.5/30], Red,
Disk[{#, i/15. + 1/60.}, 0.01] & /@ #[[6]], Black,
Text[#[[4]], {-0.1, i/15. + 1/60.}]}] &, Reverse@chrpos]
PlotSequence
Clear["Global`*"]
With computable data we can have access to historical as well as real-time weather information: WeatherData, WeatherForecastData, AirTemperatureData, AirPressureData, WindSpeedData, WindDirectionData, WindVectorData.
The command Function["location", "property", {start, end, step}] returns the value of the variable specified in “property” for a given location and period (by default it returns the most recent value).
In this example we get the average daily temperature in Salamanca (Spain) from January 1, 1995 to December 31, 2015 and represent it graphically. Notice the seasonality.
DateListPlot
[AirTemperatureData [Entity ["City", {"Salamanca", "Salamanca", "Spain" }],
{{2015, 1, 1}, {2015, 12, 31}, "Day"}]]
The commands below show how to obtain a weather station code and visualize the range of daily temperatures over the past 180 days that corresponds to that station code.
WeatherData[
Entity["City", {"Salamanca", "Salamanca", "Spain"}], "StationName"]
LESA
DateListPlot[(WeatherData["LESA", #1,
{DateString[DatePlus[-180]], DateString[DatePlus[0]], "Day"}] &) /@
{"MeanTemperature", "MaxTemperature", "MinTemperature"},
Joined → {True, False, False}, Filling → {2 → {3}}, Mesh → All]
Here we display the forecast for the following week:
Manipulate[data = WeatherForecastData ;
DateListPlot[data[g] /. Interval[x_] :→ Mean[x], FrameLabel → Automatic],
{g, {"Temperature", "WindSpeed", "WindDirection", "PrecipitationAmount"}},
SaveDefinitions → True.
The function that follows (obtained from the WindVectorData examples) returns wind data (speed and direction), at the moment of the query, for the coordinates 35ºN and 45ºN, in latitude and -10º W and 5º W in longitude (includes the Iberian peninsula and the Balearic islands). To do that we are going to use CountryData and WindVectorData in combination with ListStreamPlot. stationnames
stationnames =
DeleteDuplicates[Flatten[Table[WindVectorData[{y, x}, "StationName"],
{x, -10.0, 5.0, 1}, {y, 35.0, 45.0, 1}]]];
windVelocity[station_] :=
Module[{coords = First@WindVectorData[station, "Coordinates"]},
{Reverse@coords, -Reverse@QuantityMagnitude[WindVectorData[station]]
{1/Cos[coords[[2]] °], 1}}]
windData = windVelocity[#] & /@ stationnames //
Cases[#, u_ /; FreeQ[u, "NotAvailable"]] &;
Show[ListStreamPlot[windData, VectorStyle → Black, AspectRatio → 1],
Graphics[{GrayLevel[.2], AbsoluteThickness[1.5],
CountryData["Spain", "FullPolygon"] /. Polygon → Line}]]
Clear["Global` *"]
Use Outer to get several properties for a set of entities.
Outer [f, {x, y, z }]
{{f[a, x], f[a, y], f[a, z]}, {f[b, x], f[b, y], f[b, z]}}
Here we obtain the life expectancy in Spain, USA, France and Mexico using CountryData . The result is displayed in which each country is represented by its flag.
data = Outer[CountryData, {"Spain", "UnitedStates", "France", "Mexico"},
{"LifeExpectancy", "FemaleLifeExpectancy", "MaleLifeExpectancy"}];
flags = {
ImageResize[CountryData["Spain", "Flag"], 50],
ImageResize[CountryData["UnitedStates", "Flag"], 50],
ImageResize[CountryData["France", "Flag"], 50],
ImageResize[CountryData["Mexico", "Flag"], 50]};
BarChart3D[data,
ChartElementFunction → "Cylinder", ChartStyle → "Pastel",
ChartLegends → {"Life Expectancy(\!\(\*Cell[\"♀ + ♂\"]\))",
"Female (♀)", "Male (♂) "},
ChartLabels → {Placed[flags, {.5, 0, 1.15}], Placed[
{"\!\(\*Cell[\"♀+♂\"]\)", "♀", "♂"}, Center]}, BarSpacing → {.1, .6},
PlotLabel → Style["Life expectancy", 16, FontFamily → "Times"],
ImageSize → Large]
Clear["Global` *"]
There are many functions available for the computation of data related to the earth sciences.
We can get an idea of them by asking Mathematica to show us all the functions that start with the letter Geo (output omitted).
? Geo*
The names of the functions shown enable us to identify those related to geography, almost all of them except the ones starting with Geometric. We can always access the help documentation to see their syntax. Let’s take a look at some of them.
Using the below functions you can find your current geolocation and the name of the city of your computer.
{FindGeoLocation[], GeoIdentify[]}
FindGeoLocation[] may use built-in GPS or other capabilities. Alternatively, it may also use geoIP lookup through the Internet. Different methods may give results with different accuracy.
Next we use GeoPosition and GeoGraphics to first find the coordinates (latitude and longitude) of that location and then visualize its geographical image in 2D (the easiest way to do it is to copy and paste the first element of the output returned by the previous command as the argument for both commands). Remember that in many cases you will find the free-form input very useful as well (Insert ► Inline Free-form Input and type Salamanca).
GeoPosition[{40.97, −5.67}]
Here we display a map of Salamanca (a City of Spain) and its surroundings.
GeoGraphics [GeoVisibleRegionBoundary
[GeoPosition[{40.97, -5.67, Quantity[0.1, "Kilometers"]}]]]
The commands below return the elevation of Salamanca above sea level in meters, inform us about the minimum and maximum elevations, and create a relief plot:
ReliefPlot[elevation, DataReversed −> True,
ImageSize −> 500, ColorFunctionScaling −> False,
ColorFunction −> ColorData["HypsometricTints"],
PlotLegends −> Placed[Automatic, Below]]
We can also make a 3D plot:
ListPlot3D[Reverse[elevation],
ImageSize −> 500, ColorFunctionScaling −> False,
ColorFunction −> ColorData["HypsometricTints"],
BoxRatios −> {2, 1, 1/2},
PlotTheme −> {"FilledSurface", "Minimal"}, PlotRange → All]
Here we use that approach to see the closest locations to Salamanca:
Shown below is an example of how to zoom out of the location of Salamanca in a series of relief maps:
GeoGraphics[{Red, PointSize[Large], Point[]},
GeoZoomLevel → #, GeoBackground → GeoStyling["ReliefMap"]] & /@ {6, 4, 2}
Quite often, the data related to the United States is more complete than for other world locations. For example: New Orleans seems to have many more buildings and monuments of interest than London or Paris. We hope that the information about places of interest outside the US will be expanded in the future.
This example returns the location of all the earthquakes that happened in Chile between 2011-1-1 and 2016-6-30 with magnitudes between 6 and 10:
data = EarthquakeData[Entity["Country", "Chile"],
{6, 10}, {{2011, 1, 1}, {2016, 6, 30}}, "Position"]
GeoListPlot[data]
GeoListPlot can generate maps for locations outside the Earth. Here we visualize the landing of Apollo 11, the first manned lunar landing mission:
To make the visualization of the information easier, we use GeoRegionValuePlot to represent the values on a map. We can use "MissingStyle" → Color for those cases where there are no available data.
We use CountryData and GeoRegionValuePlot to show the Literacy Rate in the world.
map = GeoRegionValuePlot[CountryData[] → "LiteracyRate",
ColorFunction → ColorData["LightTemperatureMap"],
"MissingStyle" → White, PlotLegends → None]
Next, we project the previous map onto a sphere. To rotate it just click inside.
ParametricPlot3D[{Cos[u] Sin[v], Sin[u] Sin[v], Cos[v]} ,
{u, 0, 2 Pi}, {v, 0, Pi}, Mesh → None, Boxed → False,
TextureCoordinateFunction → ({#4, 1 - #5} &),
PlotStyle → Texture[Show[map, ImageSize → 1000]],
Lighting → "Neutral", Axes → False, RotationAction → "Clip"]
The following example uses EntityClass to display the identity class that corresponds to the given name, in this case Europe. Therefore, it includes all the European nations except Russia which has most of its territory in Asia.
EntityClass["Country", "Europe"]
Now we use EntityList to see the “Entities” included in the “Europe” class.
With EntityValue we can see the properties available for a given entity, in this case for the European countries.
The complete output, not shown here due to its length, includes emissions of greenhouse gases (GreenhouseEmissions). To see those emissions per country we can type:
In the last example of the section we combine several functions to show some travel routes originating in Salamanca. We first define the cities that we want to travel to. When typing the city is better to add the country to avoid ambiguities in case there are several cities with the same name.
{"London, England", "Nuuk, Greenland", "Buenos Aires, Argentina", "Los Angeles", "Malmo, Sweden", "Ulan Bator, Mongolia", "Sidney, Australia"}
We can use CloudDeploy in combination with GeoGraphics to build a web application.
The command below generates a map of a chosen location (we will normally enter the name of a city) and its surroundings for a given radius:
CloudDeploy[
FormFunction[{"Location" −> "Location", "Radius" −> "Quantity"},
GeoGraphics[GeoDisk[#Location, #Radius]] &, "PNG"]]
CloudObject[https://www.wolframcloud.com/objects/ed8baf92-f7b2-445f-9d60-82
We can now copy this newly created link to our website to make it accessible from any device with web browsing capabilities:
< a href = "https://www.wolframcloud.com/objects/..." > City Map (html) < /a >
The application is now available to any user, although the first time we access it, we may have to enter our Wolfram ID and password. However, we don't need to have Mathematica installed in our computers. Once we enter the required data (Figure 5.1) we get the corresponding map (Figure 5.2).
The first time you execute a data collection function, it will usually take a long time. After that, the data will be stored in your computer to speed up subsequent computations. The cached data are located in:
SystemOpen [FileNameJoin [{$UserBaseDirectory, "Paclets"}]]
Occasionally, you might want to rebuild the cached paclet information. The following command rescans the paclet directories and rebuilds the cached indexes for each paclet.
RebuildPacletData[]
If you want to force Mathematica to work from your cached directories and avoid automatic updates (useful during presentations, for example), you can turn this feature off with an internal function:
PacletManager`$AllowDataUpdates = False
To access the following resources, if they refer to the help files, write their locations in a notebook (e.g., guide/EarthSciencesDataAndComputation), select them and press <F1>. In the case of external links, copy the web addresses in a browser:
Working with data collections tutorial:
http://library.wolfram.com/infocenter/Conferences/7196
Astronomical Data: guide/AstronomicalComputationAndData
Earth Sciences: guide/EarthSciencesDataAndComputation
EngineeringData: guide/EngineeringData
Financial and Economic Data: guide/FinancialAndEconomicData
Geodesy: guide/Geodesy
GeoGraphics:tutorial/GeoGraphics
Life Sciences and Medicine: guide/LifeSciencesAndMedicineDataAndComputation
Socioeconomic Data: guide/SocioeconomicAndDemographicData
Physics and Chemistry: guide/PhysicsAndChemistryDataAndComputation
Transportation Data: guide/TransportationData
WordData: ref/WordData