Adding Object-Oriented Capabilities To Mathematica

Transcription

Adding Object-OrientedCapabilities to MathematicaHilarie NickersonFall 2011OPIM 7815Adding OO to MathematicaUniversity of Colorado at Boulder

RoadmapAbout Mathematica EnvironmentLanguage featuresProgramming paradigmsWhat might object-oriented Mathematica be like? Onging efforts to add capabilitiesThe Objectica add-onDiscussion of object orientation in Mathematica EmergenceBest usesResources2Adding OO to MathematicaUniversity of Colorado at Boulder

MathematicaWhat is it? Software for making computations and visualizing results Interactive exploration is a key featureOriginally developed and released by Stephen Wolfram in1988; now sold by Wolfram ResearchWho uses it? Millions of users STEM / MedicineBusinessSocial sciencesEducationArts“Mathematica has become a standardin a great many organizations, and itis used today in all of the Fortune 50companies, all of the 15 majordepartments of the U.S. government,and all of the world’s 50 largestuniversities.”3Adding OO to MathematicaUniversity of Colorado at Boulder

Mathematica4Adding OO to MathematicaUniversity of Colorado at Boulder

Mathematica: EnvironmentInteractive user interfaces Notebooks Evaluate expression in any cell, see results immediatelyMay include explanatory textMathematica help files are also notebooksWorkbench (Eclipse IDE)Web-based player for local and remote content Replaced desktop-based playerComputation engine Kernel accessible from above interfaces andas a service to other programs5Adding OO to MathematicaUniversity of Colorado at Boulder

Mathematica: EnvironmentNested cells: an expressionand its evaluation result6Adding OO to MathematicaUniversity of Colorado at Boulder

Mathematica: Environment7Adding OO to MathematicaUniversity of Colorado at Boulder

Mathematica: EnvironmentInteractive user interfaces Notebooks Evaluate expressions in cells, see results immediatelyMay include explanatory textMathematica help files are also notebooksWorkbench (Eclipse IDE)Web-based player for local and remote content Replaced desktop-based playerComputation engine Kernel accessible from above interfaces andas a service to other programs8Adding OO to MathematicaUniversity of Colorado at Boulder

Mathematica: Language FeaturesNumerous built-infunctions and libraries Chooses best algorithmScoping Modules(lexical scoping)Blocks(dynamic scoping, lesscommonly used)String / list manipulationRules and patternmatchingSymbolic computation Exception handling9Adding OO to MathematicaUniversity of Colorado at Boulder

Mathematica: Programming ParadigmsMajor paradigms ProceduralFunctionalObject-oriented (or so they say )Additional paradigms List-basedRule-basedString-based10Adding OO to MathematicaUniversity of Colorado at Boulder

Object-OrientedMathematicaWolfram’s early claims of object-oriented capabilitieshave faded over time Then “It is very easy to do object-oriented programming inMathematica. The basic idea is to associate Mathematicatransformation rules with the objects they act on ratherthan with the functions they perform.”— The Mathematica Book, First Edition Now11Adding OO to MathematicaUniversity of Colorado at Boulder

Object-OrientedMathematica: Built-In CapabilitiesStill not giving up 12Adding OO to MathematicaUniversity of Colorado at Boulder

Object-OrientedMathematica: Built-In CapabilitiesStack example using TagSet (/: ) stackobj /: push[stackobj[stack , item ]] : Append[stack, item];stackobj /: pop[stackobj[stack ]] : Most[stack];mystack {1, 2, 3}myitem 4mystack push[stackobj[mystack, myitem]] {1, 2, 3, 4}mystack pop[stackobj[mystack]] {1, 2, 3}mystack pop[stackobj[mystack]] {1, 2}In web forums, highly experienced Mathematica programmerssuggest that inheritance, etc. is possible; no examples found13Adding OO to MathematicaUniversity of Colorado at Boulder

Object-OrientedMathematica: Ongoing Enhancement Efforts1988Mathematica released1993Roman Maeder’s Classes.m package2002Hermann Schmitt’s OO System for Mathematica2005Orestis Vantzos’ OOP package2008Stephan Leibbrandt’s Objectica package2010Ross Tang’s MathOO package14Adding OO to MathematicaUniversity of Colorado at Boulder

Object-OrientedMathematica: Ongoing Enhancement EffortsMaeder (1993), Leibbrandt (2008) packagesmost significant Sanctioned in some way by WolframAvailable as add-onsOther packages offered by Mathematica enthusiasts Some Q&A in user communityVarying levels of capability, documentationSyntactic differences (as would be expected) MaederVantzosLeibbrandttranslateBy[sphere1, {1, 0, 0}]sphere1::translateBy[{1, 0, 0}]sphere1.translateBy[{1, 0, 0}]15Adding OO to MathematicaUniversity of Colorado at Boulder

Object-OrientedMathematica: Maeder’s Classes.mFirst serious effort at an add-on Originally promising, but Weakly documentedSupport later withdrawnSample code “Mathematica will surelybecome the prototyping toolpar excellence for objectoriented programming.”Class[ Account, Object,— Mastering Mathematica{bal, own},{{new, (new[super]; bal #1; own #2)&},{balance, bal&},{deposit, Function[bal #1]},{withdraw, Function[bal - #1]},{owner, own&}}]16Adding OO to MathematicaUniversity of Colorado at Boulder

Object-OrientedMathematica: The Objectica Add-OnWhat is it? Package for adding object-oriented features to Mathematica Sales literature emphasizes “abstract data types, inheritance,encapsulation, and polymorphism”Developed by Stephan Leibbrandt in 2008; sold bySymbols and Numbers (Germany)Who uses it? Size of userpopulationunclear“Typical Users Software engineers of other objectoriented languages for building prototypes Developers of big Mathematica projectsin order to structure the problem Engineers to image real objects”17Adding OO to MathematicaUniversity of Colorado at Boulder

Object-OrientedMathematica: The Objectica Add-OnAbstract data types Confusing terminology here; should really say abstractbase classes, which are appropriately implementedInheritance and polymorphism Clear syntax, handled wellEncapsulation Some difficulties here with respect to class / subclassrelationships (see Virtual later on)Can hide data and methods with Private option18Adding OO to MathematicaUniversity of Colorado at Boulder

Object-OrientedMathematica: The Objectica Add-OnMore features Interfaces Very much like abstract classesClasses can use multiple interfaces, but can have only oneparent classAnonymous classes Available, but poorly documentedOverall assessment Implements object orientation well, aside fromencapsulation (open to programmer error)Well-documented, for the most part19Adding OO to MathematicaUniversity of Colorado at Boulder

Object-OrientedMathematica: The Objectica Add-OnComparison with other cDynamicDynamicInheritanceSingle withmixinsSingle withinterfacesMultipleSingle withinterfacesMethodNooverloadingYesNoYesClass vars& methodsYesNoYesYes20Adding OO to MathematicaUniversity of Colorado at Boulder

Object-OrientedMathematica: Objectica Usage BasicsPackage loading options Needs["Class Class "] Get["Class Class "] Get[" path to Class.m "] Note use of Class continues (name originated by Roman Maeder)21Adding OO to MathematicaUniversity of Colorado at Boulder

Object-OrientedMathematica: Objectica Usage BasicsClass definitionSubclass definition Class[base] : {Virtual.st 0,f[x ?Positive] : x 2,f[x ?Negative] : x 3 st} Class[child, base] : {st 20,f[x ?Positive] : x,g[y ] : Sin[y]} Default constructorcreatedUse Virtual to ensurethat child’s instance ofst is accessed whenf[x ?Negative] is called More explicit versionusing Override Class[child, base] : {Override.Virtual.st 20,Override.f[x ?Positive] : x,g[y ] : Sin[y]}Good practice in casechildren come later22Adding OO to MathematicaUniversity of Colorado at Boulder

Object-OrientedMathematica: Objectica Usage BasicsCreating a new object baseObj New.base[] Note use of dot notation Alternatively, New[baseObj].base[]Redefining class to include constructor Class[base] : {Virtual.st 0,base[st ] : (This.st st),f[x ?Positive] : x 2,f[x ?Negative] : x 3 st}baseObj1 New.base[10]23Adding OO to MathematicaUniversity of Colorado at Boulder

Object-OrientedMathematica: Objectica Usage BasicsSetting an instance variable baseObj.st 100;Calling a method baseObj.f[-5]24Adding OO to MathematicaUniversity of Colorado at Boulder

Object-OrientedMathematica: Objectica Usage BasicsAbstract class with polymorphism Class definition (note use of Abstract) Alternatively, define in one step Abstract.Class[Room] : { }Subclass definitions (note use of Super) Class[Room] : { }SetAttributes[Class[Room], Abstract]Class[Single, Room] : { Single[person String] : Super[person] }Class[Double, Room] : { }Calling Price method polymorphically New.Single["Mr. Smith"].Price[]New.Double["Mr. Smith", "Mrs. Smith"].Price[]25Adding OO to MathematicaUniversity of Colorado at Boulder

Object-OrientedMathematica: Objectica Usage BasicsClass with interfaces Interface[one] : {f[x ] : 0};Interface[two] : {g[x ] : 0};Class[base2] : {h[x ] : x 2};Class[child, base2, one, two] : {Override.f[x ] : x 3,Override.g[x ] : x 4};An anonymous class New.base[].{ }26Adding OO to MathematicaUniversity of Colorado at Boulder

Object-OrientedMathematica: Objectica Usage BasicsPublic, protected, and private data Class[base3] : {e[x ] : x 2,Public.f[x ] : x 3,Protected.g[x ] : x 4,Private.h[x ] : x 5};any callerchild classesthis classAlternatively, SetAttributes[Room.Persons, Private]Class method definition and call Class[base4] : {Static.z[x ] : x 2}base4.z[5]27Adding OO to MathematicaUniversity of Colorado at Boulder

Object-OrientedMathematica: Objectica Usage ExampleStack example, revisited Class[stackobj2] : {Virtual.stack {},stackobj2[stack ] : (This.stack stack),push[item ] : stack Append[stack, item],pop[] : stack Most[stack]}mystack2 New.stackobj2[{1, 2, 3}]mystack2.push[myitem] {1, 2, 3, 4}mystack2.pop[] {1, 2, 3}28Adding OO to MathematicaUniversity of Colorado at Boulder

Object-OrientedMathematica: DiscussionWhy so slow to emerge? Existing programming paradigms are powerfulMathematica programmers know workarounds Rules, patternsInterfaces to OO languages such as Java, C Big shift in thinking required (and not desired) E.g., pushback on new OO graph features in Mathematica 8Best uses Large applications with significant complexityReal-world applications with hierarchical structureUser interface programmingSituations where encapsulation would be helpful29Adding OO to MathematicaUniversity of Colorado at Boulder

Resources for Further ExplorationMathematica’s built-in object-oriented abilities The Mathematica Book, First Editionsection on “object-oriented” contents/4.1.6.pdf Online documentation of “object-oriented” functionality UpSet.html /TagSet.htmlMathematica linking to object-oriented languages dExternalProgramCommunicationOverview.html30Adding OO to MathematicaUniversity of Colorado at Boulder

Resources for Further ExplorationObjectica product pages s/objectica/ Symbols and Numbershttp://www.objectica.net/Objectica presentations From Symbols to Objects2010 Wolfram Technology nferences/7871/ Object-Oriented Modeling with Objectica2007 Wolfram Technology nferences/6923/31Adding OO to MathematicaUniversity of Colorado at Boulder

Resources for Further ExplorationOther efforts Roman Maeder’s Classes.m package The Mathematica Journal 3:1, pp. 23-31 es/3243/ Gray, J., Mastering Mathematica, chapter 9 Maeder, R. The Mathematica Programmer, chapter htmls/1-04.htm Hermann Schmitt’s OO System for Mathematica An OO System for Mathematica, Version 3http://www.schmitther.de/oosys en/introduction.html32Adding OO to MathematicaUniversity of Colorado at Boulder

Resources for Further ExplorationOther efforts Orestis Vantzos’ OOP package From Symbols to Objects2005 Wolfram Technology nferences/5773/ Ross Tang’s MathOO package Code / Additional documentationhttp://www.voofie.com/concept/MathOO/ Read in date order, not display order33Adding OO to MathematicaUniversity of Colorado at Boulder

CreditsSlide 4 pictures nstrations.wolfram.com/SurfacesAndGradients/Slide 6 notebook /Notebooks/pendulum.nbSlide 7 pictures Mathematica documentation34Adding OO to MathematicaUniversity of Colorado at Boulder

CreditsSlide 9 picture SymbolicComputation.htmlSlide 12 pictures Mathematica documentationSlide 16 code 3/Slide 20 table http://www.schmitther.de/oosys en/comp tab.htmlSlides 20–27 code Objectica documentation35Adding OO to MathematicaUniversity of Colorado at Boulder

Wolfram's early claims of object-oriented capabilities have faded over time Then Now "It is very easy to do object-oriented programming in Mathematica. The basic idea is to associate Mathematica transformation rules with the objects they act on rather than with the functions they perform." — The Mathematica Book, First Edition 12