Introduction
Over the past few weeks, we at TI-Planet spareheaded a port of a Python derivative, namely Micro Python (after an initial attempt using the older, more limited "p14p" python-on-a-chip), to the Nspire platform. The bulk of the work was done by Fabian "Vogtinator" Vogt. The motivation was the fact that Python's usage keeps raising in school classes - it's replacing Java as first programming language in many places - whereas Lua is virtually unknown for such a use case.
Now that we've written a third article about Nspire Micro Python, this one being oriented towards actual usage of the tool for STEM purposes, we'd like to introduce that program to a wider audience Smile
This article is arguably lengthy, but it hopefully has some meaningful content.

Prerequisites for Nspire Micro Python
First of all, a small reminder: in order to leverage the full power of the Nspire platform, Micro Python requires the famous Ndless jailbreak, and therefore the OS 3.1.0.392 ("3.1") or OS 3.6.0.546/550 ("3.6") versions. Unfortunately, it's not always easy, or even possible at the time of this writing, to get back to versions older than the current 3.9.0.461/463 OS versions. A description of the set of situations follows:
  • if you have a CX (CAS) calculator with OS 3.9, that came with hardware revision J or later (the hardware revision being the letter (last character) of the code at the back of the calculator), i.e. any CX calculator bought brand-new since the spring of 2013, you can sadly, skip the rest of this post: using Micro Python is currently impossible on such calculators... use DowngradeFix 3.9 to downgrade to OS 3.6. You can keep sending protest e-mails to ti-cares@ti.com , a template (translated to English) is suggested at the end of previous news item about Micro Python.
  • if you have a CX (CAS) calculator, and it's running the boot2 3.1.0.16 version, then it's an old enough hardware revision, and you can additionally use nLaunchy to move up and down the OS versions as you wish, as long as you keep the 3.1.0.16 boot2 version;
  • if you have a CX (CAS) calculator, of original or A to I hardware revision, and it's running the 3.9 OS and therefore the boot2 3.2.4.7 version, you need to use DowngradeFix 3.9 to downgrade to OS 3.6, or downgrade the boot2 through cheap, extra equipment known as "USB / RS232 TTL adapter", (see tutorial (french)).
  • if you have a Clickpad or Touchpad (CAS) calculator, and it's running the boot2 1.1 or 1.4.1571 versions, you can move up and down the OS versions as you wish, thanks to DowngradeFix and nLaunchy;
  • f you have a Clickpad or Touchpad (CAS) calculator with OS 3.9, and it's running the boot2 3.1.131 version, you need to downgrade the boot2 through cheap, extra equipment known as "USB / RS232 TTL adapter", (see tutorial (french)).

Micro Python programs are Python programs
They can be written on the computer with any text editor / IDE that supports Python, then transferred to the calculator using TINC(L)S or TILP (after adding the .tns extension required for the transfer process), and/or modify them on the calculator side thanks to editors such as nTxt.

Let's start with a well-known example: recursive computation of the Fibonacci sequence's terms. The code is very simple, but the number of inner calls is exponential in the argument passed to the function, which makes the recursive Fibonacci computation a highly classic simple benchmark. For practical purposes, an iterative computation of the Fibonacci sequence's terms, whose code is barely more complex, is much more efficient than the recursive computation, as it has linear complexity.
Nothing fancy in the program's code.
Nspire Basic:

Code:
Define fibo(n)
Func
    If (n <= 1) Then
        return n
    Else
        return fibo(n-1)+fibo(n-2)
    EndIf
EndFunc

fibo(30)

Nspire Lua:

Code:
function fibo(n)
    if (n <= 1) then
        return n
    else
        return fibo(n-1)+fibo(n-2)
    end
end

print(fibo(30))

Nspire Micro Python

Code:
def fibo(n):
    if (n <= 1):
        return n
    else:
        return fibo(n-1)+fibo(n-2)

print(fibo(30))

Unsurprisingly, the execution performance of the Python program is similar to that of the equivalent Lua program; the Basic program is far behind.



Other examples
Numerical base conversion
Returns list of the "figures" of the representation of in the b base
The most significant figure is leftmost

Nspire Basic:

Code:
Define baseb(n,b)=
Func
Local rep
{}->rep
While n>0
  augment({mod(n,base)},rep)->rep
  intdiv(n,base)->n
EndWhile
Return rep
EndFunc

Nspire Lua:

Code:
function baseb(n, b)
    local t = {}
    local tmp = 0
    while n > 0 do
        n, tmp = math.floor(n/b), n%b
        table.insert(t, 1, tmp)
    end
    return t
end

Nspire Micro Python:

Code:
def baseb(n, b):
    t = []
    while n > 0:
        n, tmp = divmod(n, b)
        t = [tmp] + t
    return t


Compute Pi digits
Returns a string containing the n first digits of Pi
Nspire Basic:

Code:
Define cpi(n)=
Func
Local a,b,a1,b1,a0,b0,s,p,q,d,d1
4->a:1->b
12->a1:4->b1
""->s
1->p:3->q
While n >= 0
  p+q->p: q+2->q
  a->a0: b->b0
  a1->a: b1->b
  p*a0+q*a1->a1
  p*b0+q*b1->b1
  intdiv(a,b)->d
  intdiv(a1,b1)->d1
  While d = d1 and n >= 0
    s & string(d)->s
    n-1->n
    10*mod(a,b)->a
    10*mod(a1,b1)->a1
    intdiv(a,b)->d
    intdiv(a1,b1)->d1
  EndWhile
EndWhile
Return left(s,1)&","&mid(s,2)
EndFunc

Nspire Lua:

Code:
local floor = math.floor

function cpi(n)
    -- Wrong starting from the 25th digit !
    -- Crashes TINCS if > 109 !
    local a, b, a1, b1 = 4, 1, 12, 4
    local s = ""
    local p, q = 1, 3
    while n >= 0 do
        p, q = p+q, q+2
        a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
        d, d1 = floor(a/b), floor(a1/b1)
        while d == d1 and n >= 0 do
            s = s .. d
            n = n-1
            a, a1 = 10*(a%b), 10*(a1%b1)
            d, d1 = floor(a/b), floor(a1/b1)
        end
    end
    return s:sub(1,1) .. "," .. s:sub(2)
end

Nspire Micro Python:

Code:
def cpi(N):
    a, b, a1, b1 = 4, 1, 12, 4
    s = ""
    p, q = 1, 3
    while N >= 0:
        p, q = p+q, q+2
        a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
        d, d1 = a//b, a1//b1
        while d == d1 and N >= 0:
            s += str(d)
            N -= 1
            a, a1 = 10*(a%b), 10*(a1%b1)
            d, d1 = a//b, a1//b1
    return s[0] + "," + s[1:]


List of the first prime numbers (Eratostenes' sieve)
Returns the list of the prime numbers lower than or equal to n using Eratostenes' sieve
Nspire Basic:

Code:
Define primes_list(n)=
Func
Local t,r,i,j
seq(when(i=1 or (mod(i,2)=0 and i>2),_,i),i,1,n)->t
floor(sqrt(n))->r
3->i
While i <= r
  If not(isvoid(t[i])) Then
    For j,i^2,n,i
      _->t[j]
    EndFor
  Endif
  i+2->i
EndWhile
Return delvoid(t)
EndFunc

Nspire Lua:

Code:
-- Modified from http://rosettacode.org
function primes_list(n)
    if n < 2 then return {} end
    local t = {false} -- init
    local max = math.sqrt(n)
    for i = 2, n do
        t[i] = true
    end
    for i = 2, max do
        if t[i] then
            for j = i*i, n, i do
                t[j] = false
            end
        end
    end
    local primes = {}
    for i = 2, n do
        if t[i] then
            primes[#primes+1] = i
        end
    end
    return primes
end

Nspire Micro Python:

Code:
# From http://rosettacode.org
def primes_upto(limit):
    is_prime = [False] * 2 + [True] * (limit - 1)
    for n in range(int(limit**0.5 + 1.5)):
        if is_prime[n]:
            for i in range(n*n, limit+1, n):
                is_prime[i] = False
    return [i for i, prime in enumerate(is_prime) if prime]


As far as the execution speed of the programs is concerned, the Basic is still way behind Lua and Python. Those two are quite equal on that (generally Python can be a bit faster), though, but when the "JIT"-like mode is enabled (native code emission), Python takes the lead.

Notice the similarity of the Python and Lua languages. Python has some extra syntactic sugar which makes it possible to use single statements / lines for some operations...

The Nspire's BASIC has always been an exception among graphing calculators' respective languages, much to programmers' chagrin: no pixel drawing commands, no direct keyboard reading... In 2011, Lua plugged this hole, even if it could have been made more powerful. In 2014, Micro Python can do better, for instance with access to the full screen area. Vogtinator started making a small graphical API, and applying it to the drawing of a Mandelbrot fractal (source code):



Comparison between the programming languages available on the Nspire (at the time of this writing):

(original table: http://tiplanet.org/forum/viewtopic.php?p=170689#p170689 , using special markup on TI-Planet)
(*): CAS integration is hard without documentation from TI, even if Lionel Debroux and Excale made PoC programs.

We hope to have provided a decent overview of the venues offered by Micro Python in STEM, and have made you eager to use it. At least, those of you who can because they're not using OS 3.9 yet and cannot downgrade anymore (easily, or at all)...


Looking forward...
Community contributions to improve the use of Micro Python Nspire (bug reports, feature requests, code contributions) are of course welcome. We're far less restricted on features and implementation than with TI's Lua. We could dream of:
  • an expanded graphical API;
  • a Python code editor sporting better integration into the OS, such as a Python variant of Jens' Script (Lua) Editor using a Lua native code extension to read and write files freely (basic functionality which TI's Lua simply cannot do);
  • even an interoperability with Lua code through native code, at least one-way interoperability ?




We already indicated that we're also dreaming of TI officially offering Python to users, possibly under plugin form, like the English-Chinese dictionary for CX-C is. Of course, it would be even better if TI made a U-turn from the way the Nspire was handled over the past 7 years and quit fighting the power of native code on the Nspire - for the students' sake !


Links :
- MicroPython for the TI-Nspire (Note : an unstable version with the drawing API and native code emission is available via the description in the archive page)
- Source code of the Nspire fork : on GitHub




Article written mainly by Lionel Debroux and Adriweb, translated by Lionel. Example program source codes: Adriweb, Bisam.
Originally posted at http://tiplanet.org/forum/viewtopic.php?f=43&t=15309&lang=en , formatting of this post changed for Cemetech's markup.

Previous TI-Planet articles about Nspire Micro Python: https://tiplanet.org/forum/viewtopic.php?f=43&t=15140&lang=en (in English, initial announcement with detailed explanations about the motivations), https://tiplanet.org/forum/viewtopic.php?f=43&t=15191 (in French only, more focused on the French educational system)
This is fantastic =) - does MicroPython have any support for Cython?
This is excellent work; I'm glad Fabian "Vogtinator" Vogt succeeded in porting a Python interpreter to the TI-Nspire. Given that Ndless allows native code execution, I figured it was just a matter of time before someone took the time to port existing code to the TI-Nspire. For the non-graphical components, I assume that the effort was relatively sane, given that a standard library of sorts already existed? I am curious if the fledgling graphical library mirrors the Lua graphical libraries the Nspire offers in any way to make transitioning between the two languages simpler.

Needless to say, this inspires me to wonder what we could do with the TI-84 Plus C Silver Edition and Python.
Quote:
does MicroPython have any support for Cython?

I'm not sure to understand what you mean by that Smile
The pure Python libs associated with Cython ? The native libs associated with Cython ?
There's https://github.com/micropython/micropython-lib , but it isn't very complete.

Quote:
This is excellent work; I'm glad Fabian "Vogtinator" Vogt succeeded in porting a Python interpreter to the TI-Nspire.

He ported two, as he started with p14p as we suggested (I had ported it to the TI-68k/AMS platform), but nowadays, Micro Python is a much better choice.
He contributed various improvements to upstream Micro Python, starting with a native ARM JIT code emitter. Micro Python contained a Thumb-2 JIT emitter, but that doesn't fly for an old ARM926EJ-S.

Quote:
Given that Ndless allows native code execution, I figured it was just a matter of time before someone took the time to port existing code to the TI-Nspire.

The main roadblock used to be the toolchain and standard library, which was not based onto newlib until recently. The work was made for porting GIAC to the Nspire, yielding KhiCAS (pun intended by Bernard Parisse, with a Lua UI made by Adriweb among others), and easing other similar ports a fair bit.

Quote:
For the non-graphical components, I assume that the effort was relatively sane, given that a standard library of sorts already existed?

There are "only" seven functions for now: display (copies to the screen), fill, setPx, getPx, drawOnto (blitting), setData, delete.
The implementation is independent from the OS or existing standard libraries, AFAICT.

Quote:
I am curious if the fledgling graphical library mirrors the Lua graphical libraries the Nspire offers in any way to make transitioning between the two languages simpler.

Mildly hard to say for now, but it's clearly a goal worth pursuing.

Quote:
Needless to say, this inspires me to wonder what we could do with the TI-84 Plus C Silver Edition and Python.

Yup.
The code and data of Micro Python would be a large app on the 84+CSE, and take up some RAM, too.
The Micro Python reference board is based on a STM32F405RGT6 chip, which is far more powerful than most TI, Casio, even HP calculators on the market...
The community Arithmax E301 also leverages a Cortex-M microcontroller, and the recently announced Cortex-M7 will expand the usability range of the Cortex-M series even further.
Lionel Debroux wrote:
Quote:
does MicroPython have any support for Cython?

I'm not sure to understand what you mean by that Smile
The pure Python libs associated with Cython ? The native libs associated with Cython ?
There's https://github.com/micropython/micropython-lib , but it isn't very complete.


Cython isn't quite the same as CPython - CPython is an implementation of the Python interpreter. Cython is a compiler that produces loadable module binaries from Python code (or from a restricted dialect of Python that can be compiled more efficiently). However the binaries it produces are in the format used by libs for CPython, so your answer is still related.
Doh, Cython.
Then I don't know the answer to your question Smile
This sounds amazing!
Let me preface this question by saying that I'm a chemistry teacher and sub-novice python programmer, with some arduino experience and minimal use of TI-devices. I have put together a set of puppy linux machines running logger pro as beta for my students to collect and evaluate data on.

I would like to be able to rely on student calculators for doing the computing and this may be a great option.

Will CPython support other python libraries, specificially pyserial (need to check on TI hardware) and matplotlib?

My present setup uses vernier and other probes connected to an arduino to gather data which is then captured by a python script and evaluated using the matplotlib. It would be amazing to be able to use the TI in place of my relic laptops to increase portability of my sensors.
Quote:
Will CPython support other python libraries, specificially pyserial (need to check on TI hardware) and matplotlib?

Micro Python Lib ( https://github.com/micropython/micropython-lib ) has neither pyserial, nor matplotlib.
However, providing access to the Nspire's serial port through Nspire Micro Python is feasible. Micro Python has UART support for another board, anyway.
As for matplotlib... I strongly doubt Micro Python has plans for providing it, but you could always post the feature request.

BTW, those who worked on the TI-Nspire port of Micro Python don't read Cemetech. The main topics are on http://tiplanet.org , from where the Micro Python Nspire project originates.
Thanks for the re-direct.
Lionel Debroux wrote:
BTW, those who worked on the TI-Nspire port of Micro Python don't read Cemetech. The main topics are on http://tiplanet.org , from where the Micro Python Nspire project originates.
There's another way to fix that, you know. Wink

BCaine: Welcome to Cemetech! What kind of handhelds are you working with, out of curiosity? All TI-Nspires, or some TI-8x calculators as well?
Lionel Debroux wrote:
IntroductionUnfortunately, it's not always easy, or even possible at the time of this writing, to get back to versions older than the current 3.9.0.461/463 OS versions. A description of the set of situations follows:
[list][*]if you have a CX (CAS) calculator with OS 3.9, that came with hardware revision J or later (the hardware revision being the letter (last character) of the code at the back of the calculator), i.e. any CX calculator bought brand-new since the spring of 2013, unfortunately, you can skip the rest of this post: using Micro Python is currently impossible on such calculators.


This information isn't accurate anymore, a 3.9 downgrade has been released.
Indeed, I have updated the post and the original TI-Planet article. Thanks for the report.
Hi,
I just installed Micropython on my CX CAS and its working.
Is there a way to use (python)scipts I coded on my computer on my handheld?
As far as I could see, Micropython allows me to code on my handheld, but has no face for using existing scipts (like asking me for input after an input() command.
Can somebody help?

Greets from Germany
FGJ
Jofgur wrote:
Is there a way to use (python)scipts I coded on my computer on my handheld?

Absolutely, just create your .py on the computer, and rename it as a .py.tns (so that it will be able to be transferred).
On the calculator side, MicroPython should have registered itself as a .py handler, so if you open the file directly, it should open within MicroPython Smile
No need to downgrade anymore. ndless 4.2 runs fine on the latest TI OS. Does anyone know if there's a plan to implement the random module? I use random numbers a lot and the standard python random library is very useful to me.

Tom L
  
Register to Join the Conversation
Have your own thoughts to add to this or any other topic? Want to ask a question, offer a suggestion, share your own programs and projects, upload a file to the file archives, get help with calculator and computer programming, or simply chat with like-minded coders and tech and calculator enthusiasts via the site-wide AJAX SAX widget? Registration for a free Cemetech account only takes a minute.

» Go to Registration page
Page 1 of 1
» All times are UTC - 5 Hours
 
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum

 

Advertisement