Connectivity - Maple Programming Help

Online Help

All Products    Maple    MapleSim


Home : Support : Online Help : System : Information : Updates : Maple 2018 : updates/Maple2018/Connectivity

Connectivity

 

Python

Deep Learning with TensorFlowTM

FileTools

XMLTools

Additional Updates

Python

Maple 2018 is now packaged with a Python 3.6 kernel.

 

The Python kernel is linked to Maple. This means you can execute Python scripts, and return results to Maple.

Everyone who installs Maple will also have access to a Python interpreter with a selection of useful Python libraries.  In Maple, with(Python); loads a small set of tools to help execute commands, inspect variables, and interact with Python.

withPython;

DefineFunction,EvalFunction,EvalMember,EvalString,GetVariable,ImportModule,None,PackageTool,SetVariable,Start,Stop

(1.1)

Arbitrary strings can be parsed and evaluated:

EvalString1+1;

2

(1.2)

EvalString7 ^ 15;

8

(1.3)

EvalString7 ** 15;

4747561509943

(1.4)

EvalString15 // 2 ;

7

(1.5)

Here's a slightly longer string to parse and evaluate after importing the "statistics" package:

ImportModulestatistics;

EvalStringstatistics.median_grouped([1, 3, 3, 5, 7], interval=2)

3.50000000000000

(1.6)

Evaluating as a string is easy and flexible, but you can go even further and make Python functions look like native Maple functions:

mg  EvalStringstatistics.median_grouped;

mg ≔ <Python object: <function median_grouped at 0x7f25d11b9400>>

(1.7)

mg1&comma;3&comma;3&comma;5&comma;7&comma; interval&equals;2&semi;

3.50000000000000

(1.8)

ImportModulemath&semi;

pysin  EvalStringmath.sin&semi;

pysin ≔ <Python object: <built-in function sin>>

(1.9)

pysin1.0&semi;

0.841470984807897

(1.10)

Module :- member notation can be used to class methods:

pymath  EvalStringmath&semi;

pymath ≔ <Python object: <module 'math' from '/mnt/data/sandbox/main/ThirdParty/Python/Python-3.6.6/X86_64_LINUX/lib/python3.6/lib-dynload/math.cpython-36m-x86_64-linux-gnu.so'>>

(1.11)

pymath:-cos1.0&semi;

0.540302305868140

(1.12)

pymath:-acos1.0&semi;

0.

(1.13)

pymath:-sqrt2&semi;

1.41421356237310

(1.14)

Here is a more involved example that uses a Python package for HTML parsing and manipulation.

ImportModulefrom bs4 import BeautifulSoup

htmldoc<html><body><h1>Great Novels</h1><ul><li><a href=\"http://MiguelDeCervantes.com\">Don Quixote</a><li><a href=\"http://FyodorDostoevsky.com\">Crime and Punishment</a><li><a href=\"http://AlexandreDumas.com\">The Count of Monte Cristo</a></ul></body></html>&colon;

soupEvalFunctionBeautifulSoup&comma;htmldoc&comma;html.parser&colon;

soup:-h1:-string

Great Novels

(1.15)

seqlink:-text&comma;link in soup:-find_alla

Don Quixote&comma;Crime and Punishment&comma;The Count of Monte Cristo

(1.16)

New procedures can be defined from Maple:

EvalStringdef mysum(a,b): return a+b&comma;output=none

pysum  GetVariablemysum&semi;

pysum ≔ <Python object: <function mysum at 0x7f25d29926a8>>

(1.17)

pysum1&comma;1&semi;

2

(1.18)

Options are available to control how results come back to Maple.  Above we see 'output'='none' to prevent any result from coming back.  Next, we'll use 'output' = 'python' to avoid converting back to a Maple object; and instead capture an object reference, in this case to an empty string.  This allows us access to Python string methods in the result.

emptystringEvalString''&comma;output=python

emptystring ≔ <Python object: >

(1.19)

emptystring:-joina&comma;b&comma;c

abc

(1.20)

The Python process is in a separate memory space than Maple, and can be stopped and restarted at any time.  

EvalStringa=1\nb=2\nc=3&colon;

GetVariablea&comma; GetVariableb&comma; GetVariablec&semi;

1&comma;2&comma;3

(1.21)

Stop&semi;

true

(1.22)

Error, (in Python:-GetVariable) NameError: name 'a' is not defined |lib/Python/src/GetVariable.mm:50|

EvalString2+2&semi;

4

(1.23)

For more, see Python.

Deep Learning with TensorFlowTM

Maple 2018 includes a new package, DeepLearning, which offers an limited API to the TensorFlow toolset for machine learning using neural networks.

Example: Fitting a Curve

Here we perform least-squares regression to fit a Fourier series to a set of sample data given by:

restart&colon;
Points  0.2.11.1.52.3.13.6.34.8.25.11.56.12.77.8.4&colon;

The general formula for a Fourier series with 2 N&plus;1 terms and coefficients c&comma;a__1&comma;..&period;&comma;a__N&comma;b__1&comma;..&period;&comma;b__N is given by:

Fx&comma;a&comma;b&comma;c&comma;Nc &plus; addan cosn x &plus; bn sinn x&comma;n&equals;1..N

F ≔ x&comma;a&comma;b&comma;c&comma;N&rarr;c&plus;addancosnx&plus;bnsinnx&comma;n&equals;1..N

(2.1.1)

For this example we take N&equals;4:N  4

4

(2.1.2)

We first declare a sequence of variables in the deep learning graph corresponding to each an and bn:

withDeepLearning&colon; 

a  Array1..N&comma;iVariable0.5&comma; datatype&equals;float4&colon;

b  Array1..N&comma;iVariable0.5&comma; datatype&equals;float4&colon;

c  Variable0.5&comma; datatype&equals;float4&colon;

 

We can now define placeholders to hold the sample x- and y-values against which we want to fit Fx&comma;a&comma;b&comma;N:

x  Placeholder float4

x ≔ DeepLearning TensorName: Placeholder:0Shape: undefinedData Type: float[4]

(2.1.3)

 

y  Placeholder float4

y ≔ DeepLearning TensorName: Placeholder_1:0Shape: undefinedData Type: float[4]

(2.1.4)

We can now define a least-squares distance function which we aim to minimize:

loss ReduceSumFx&comma;a&comma;b&comma;c&comma;N y2

loss ≔ DeepLearning TensorName: Sum:0Shape: []Data Type: float[4]

(2.1.5)

optimizer  OptimizerGradientDescent0.01&semi;

optimizer ≔ DeepLearning Optimizer<tensorflow.python.training.gradient_descent.GradientDescentOptimizer object at 0x7f2f7d033cc0>

(2.1.6)

train  optimizer:-Minimizeloss&semi;

train ≔ DeepLearning TensorName: GradientDescentShape: undefinedData Type: undefined

(2.1.7)

With the structure of our deep learning graph defined, we can proceed to train it on sample data.  After initializing the session, we run 1000 training cycles using the training data.

x__training  convertPoints..&comma;1&comma;list

x__training ≔ 0.&comma;1.&comma;2.&comma;3.&comma;4.&comma;5.&comma;6.&comma;7.

(2.1.8)

y__training  convertPoints..&comma;2&comma;list

y__training ≔ 2.1&comma;1.5&comma;3.1&comma;6.3&comma;8.2&comma;11.5&comma;12.7&comma;8.4

(2.1.9)

 

 

init VariablesInitializer&colon; 

sess  Session

sess ≔ DeepLearning Session<tensorflow.python.client.session.Session object at 0x7f2f7d03c2e8>

(2.1.10)

 

sess:-Runinit&colon;

for i to 1000 do     sess:-Run train&comma; x in x__training&comma; y in y__training &colon;end do&colon;

We can now query the state of the trained model for the present value of the loss function:

sess:-Runloss&comma;x in x__training&comma; y in y__training

0.0005359374335967004

(2.1.11)

As this is a small value, we have a close fit for the data.  We can then obtain the final value of the parameters from the trained model.

result sess:-RunConcatenatea&comma;0&comma;Concatenateb&comma;0&comma;c&comma;x in x__training&comma; y in y__training

result ≔ 2.085738658905038.189836502075202.9884691238403310.7947034835815&comma;8.446731567382818.051169395446781.606976509094240.845225214958191&comma;5.61942768096924

(2.1.12)

A&comma;B&comma;C  result1&comma;result2&comma;result3

A&comma;B&comma;C ≔ 2.085738658905038.189836502075202.9884691238403310.7947034835815&comma;8.446731567382818.051169395446781.606976509094240.845225214958191&comma;5.61942768096924

(2.1.13)

Finally, we can visualize the result:
withplots&colon;

Example: Classification

Here we use a deep neural network to classify the famous Iris flower data set collected by Edgar Anderson and made famous by Ronald Fisher.  This data set includes 150 distinct observations of iris flowers, each of which consists of four empirical observations (sepal length, sepal width, petal length, and petal width) along with a classification into one of three known species (I. setosa, I. versicolor, and I. virginica).

We will repeat here the classical task for which this data set is used: attempting prediction of the species based on the four measured quantities

 

Training and Test Data
We have divided the data in into training and test data: the former is used to build the model, the latter is used to test its predictive accuracy.     

training_data  Importexample/iris_training.csv&comma;base&equals;datadir&semi;test_data  Importexample/iris_test.csv&comma; base&equals;datadir&semi;

test_data ≔ SepalLengthSepalWidthPetalLengthPetalWidthSpecies16.43.24.51.5versicolor27.135.92.1virginica35.24.11.50.1setosa47.736.12.3virginica57.73.86.72.2virginica66.12.65.61.4virginica753.51.30.3setosa85.62.74.21.3versicolor94.83.41.90.2setosa105.12.531.1versicolor`:``:``:``:``:`30 x 5 DataFrame

(2.2.1)

We see that this data set has 150 samples (120 for training and 30 for testing) and that the Species column has three distinct species:    NumRowstest_data&comma; NumRowstraining_data

30&comma;120

(2.2.2)

converttest_dataSpecies&comma;set union converttraining_dataSpecies&comma;set

setosa&comma;versicolor&comma;virginica

(2.2.3)

To simplify things we will replace the strings designating the species classification with the numbers 0,1,2 (corresponding to setosa, versicolor, and virginica, respectively):

  training_set  mapeval&comma;training_data&comma;setosa&equals;0&comma;versicolor&equals;1&comma;virginica&equals;2&semi; 

training_set ≔ SepalLengthSepalWidthPetalLengthPetalWidthSpecies162.241125.43.91.30.4035.634.11.3146.43.15.51.8254.431.30.2064.83.41.60.2075.43.91.70.40853.21.20.2094.931.40.20107.42.86.11.92`:``:``:``:``:`120 x 5 DataFrame

(2.2.4)

test_set  mapeval&comma;test_data&comma;setosa&equals;0&comma;versicolor&equals;1&comma;virginica&equals;2&semi; 

test_set ≔ SepalLengthSepalWidthPetalLengthPetalWidthSpecies16.43.24.51.5127.135.92.1235.24.11.50.1047.736.12.3257.73.86.72.2266.12.65.61.42753.51.30.3085.62.74.21.3194.83.41.90.20105.12.531.11`:``:``:``:``:`30 x 5 DataFrame

(2.2.5)

Training the Deep Neural Network Model

With our data prepared, we can now actually define and train the model.

withDeepLearning&colon;

Our first step is to define a feature for each of the four observed quantities in the test data minus the final one (species) which we aim to predict:

cols  ColumnLabelstest_set

cols ≔ SepalLength&comma;SepalWidth&comma;PetalLength&comma;PetalWidth&comma;Species

(2.2.6)

fc  map NumericColumn&comma; cols1..4&comma; shape&equals;1 

fc ≔ Feature Column_NumericColumn(key='SepalLength', shape=(1,), default_value=None, dtype=tf.float32, normalizer_fn=None)&comma;Feature Column_NumericColumn(key='SepalWidth', shape=(1,), default_value=None, dtype=tf.float32, normalizer_fn=None)&comma;Feature Column_NumericColumn(key='PetalLength', shape=(1,), default_value=None, dtype=tf.float32, normalizer_fn=None)&comma;Feature Column_NumericColumn(key='PetalWidth', shape=(1,), default_value=None, dtype=tf.float32, normalizer_fn=None)

(2.2.7)

We can now define a deep neural network classifier with these features.  It has 3 classes because there are 3 species of iris in the dataset.

classifier  DNNClassifierfc&comma; hidden_units &equals; 10&comma;20&comma;10&comma; num_classes &equals; 3&semi;

classifier ≔ DeepLearning Estimator<tensorflow.python.estimator.canned.dnn.DNNClassifier object at 0x7f2f754d3048>

(2.2.8)

We are now ready to train the model.

classifier:-Train training_set1..4&comma; training_set5&comma; steps&equals;2000&comma; num_epochs&equals;none&comma; shuffle&equals;true 

DeepLearning TensorName: noneShape: undefinedData Type: undefined

(2.2.9)

Now trained, we can evaluate the classifier on the test set, and we see that we have achieved 96.7% predictive accuracy:

results  classifier:-Evaluate test_set1..4&comma; test_set5&comma; shuffle&equals;false&comma; num_epochs&equals;1 

results ≔ accuracy0.966666638851166average_loss0.207807928323746loss6.23423767089844global_step2000

(2.2.10)

We can now build a predictor function that takes an arbitrary set of measurements as a DataSeries and returns a prediction:

predictor  procds classifier:-PredictTransposeDataFrameds&comma; num_epochs&equals;1&comma; shuffle&equals;false1 end proc&colon;

 

Using a Trained Model

With this we can take an arbitrary new point, and generate a prediction from the trained model:

ds  DataSeries5.8&comma; 3.1&comma; 5.0&comma; 1.7&comma;labels&equals;cols1..4

ds ≔ SepalLength5.8SepalWidth3.1PetalLength5.0PetalWidth1.7

(2.2.11)

predictords

logits9.358536720275881.570757389068605.12541389465332probabilities4.9826127224150710-70.02779644355177880.972203016281128class_ids2classes<Python object: b'2'>

(2.2.12)

The probabilities field in the above result records the estimated probabilities for each class.

In this case, the model estimates a 97.8% probability that this particular sample is class 2, and therefore predicts that it is I. virginica.

FileTools

The CanonicalPath command resolves any relative directories and symbolic links present in a given file path to construct a canonical version of this path.

withFileTools&colon;

CanonicalPathC:\\Users\\MapleUser\\..

/tmp/C:\Users\MapleUser\..

(3.1)

The IsLink command tests whether a given file path corresponds to a symbolic link.

IsLink/usr/local/bin/perl

Error, (in FileTools:-IsLink) file or directory does not exist |lib/FileTools/src/IsLink.mm:56|

XMLTools

ToRecord formats an XML tree as a nested record

withXMLTools&colon;

This example shows how repeated elements are put into a list, and the order they occurred can be deduced from the _order export.

xmlParseString<doc><a>1</a><b>2</b><a>3</a></doc>&colon;

rToRecordxml&colon;

Printr


  <doc>
    <a>1</a>
    <b>2</b>
    <a>3</a></doc>

r:-doc:-a1

1

(4.1)

r:-doc:-b

2

(4.2)

r:-doc:-a2

3

(4.3)

r:-doc:-_order

a&comma;b&comma;a

(4.4)

Additional Updates

The new MapleTA:-QTI command converts IMS Question & Test Interoperability (QTI) files into Maple T.A./Möbius course module.

OpenMaple enhances Java connectivity with several new commands, including toBigDecimal, toBigInteger, Relation, evalBoolean, lhs and set.