Printing#

Aside from plotting result, printing numbers is probably the main way you do science. (Or maybe your science consists entirely of listening to birdsong.) This tutorial can’t help make the numbers in your science better, but it can help you figure out more quickly if they’re good numbers or not.

Click here to open an interactive version of this notebook.

Headings and colors#

No one in their right mind would make a black and white plot these days, but it’s still pretty common to output monochrome text. Fair: color should be used sparingly. But when you do want a pop of color, Sciris has you covered. For example, you can easily make section headings to delineate large blocks of text:

[1]:
import sciris as sc
import numpy as np

sc.heading('A very long green story')
string = '"Once upon a time, there was a story that began: '
sc.printgreen(sc.indent(string*20 + ' ...'))

sc.heading('Some very dull blue data')
sc.printblue(np.random.rand(10,6))


———————————————————————
A very long green story
———————————————————————

"Once upon a time, there was a story that began: "Once upon a time,
there was a story that began: "Once upon a time, there was a story
that began: "Once upon a time, there was a story that began: "Once
upon a time, there was a story that began: "Once upon a time, there
was a story that began: "Once upon a time, there was a story that
began: "Once upon a time, there was a story that began: "Once upon a
time, there was a story that began: "Once upon a time, there was a
story that began: "Once upon a time, there was a story that began:
"Once upon a time, there was a story that began: "Once upon a time,
there was a story that began: "Once upon a time, there was a story
that began: "Once upon a time, there was a story that began: "Once
upon a time, there was a story that began: "Once upon a time, there
was a story that began: "Once upon a time, there was a story that
began: "Once upon a time, there was a story that began: "Once upon a
time, there was a story that began:  ...



————————————————————————
Some very dull blue data
————————————————————————

[[0.60962601 0.45502758 0.00702387 0.3981178  0.69297044 0.70858265]
 [0.96548873 0.48669049 0.49113069 0.53301695 0.90543058 0.20292582]
 [0.0356772  0.10433039 0.81596274 0.89185243 0.16588721 0.41033412]
 [0.56912259 0.90739313 0.62449172 0.90002498 0.31852773 0.39907302]
 [0.07340541 0.10506472 0.58416071 0.68933694 0.08875252 0.61280787]
 [0.39597145 0.72713099 0.00814399 0.87738039 0.33556999 0.99300935]
 [0.06788337 0.52535999 0.66088755 0.38413962 0.81164866 0.24275109]
 [0.44277032 0.49973582 0.75010966 0.00256875 0.52436613 0.73786257]
 [0.2712331  0.20119618 0.6154591  0.33587314 0.65418741 0.03986953]
 [0.92473798 0.71139935 0.76890299 0.91223241 0.41247221 0.40127592]]

(Note: if you’re reading this on docs.sciris.org, there’s a little button at the top right where you can change to dark mode if you prefer – the colors might make more sense then!)

Incidentally, Sciris includes two functions for combining strings: sc.strjoin() and sc.newlinejoin(). These are just shortcuts to ', '.join() and '\n'.join(), respectively (plus automatic conversion to strings), but can make life easier, especially inside f-strings:

[2]:
def get(key):
    my_dict = dict(key1=1, key2=2, key3=3)
    try:
        my_dict[key]
    except:
        errormsg = f'Invalid key {key}; must be {sc.strjoin(my_dict.keys())}, which have values:\n{sc.newlinejoin(my_dict.items())}'
        print(errormsg)

get('key4')
Invalid key key4; must be key1, key2, key3, which have values:
('key1', 1)
('key2', 2)
('key3', 3)

Printing objects#

Let’s revisit our well-trodden sim:

[3]:
import numpy as np
import matplotlib.pyplot as plt

class Sim:
    def __init__(self, n=10, n_factors=5):
        self.n = n
        self.n_factors = n_factors
        self.results = sc.objdict()
        self.ready = False

    def run(self):
        for i in range(self.n_factors):
            label = f'i={i+1}'
            result = np.random.randint(0, 10, self.n)**(i+1)
            self.results[label] = result
        self.ready = True

    def plot(self):
        plt.plot(self.results[:])

sim = Sim()
sim.run()

We can quickly view the full object with the “pretty representation”, or sc.pr():

[4]:
sc.pr(sim)
<__main__.Sim at 0x7ff9f52d4510>
[<class '__main__.Sim'>]
————————————————————————————————————————————————————————————————————————
Methods:
  plot()                  run()
————————————————————————————————————————————————————————————————————————
        n: 10
n_factors: 5
    ready: True
  results: #0. 'i=1': array([6, 0, 4, 6, 9, 6, 8, 4, 4, 3])
           #1. 'i=2': array([ 4,  [...]
————————————————————————————————————————————————————————————————————————

Compare this to the standard but less informative dir():

[5]:
dir(sim)
[5]:
['__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getstate__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 'n',
 'n_factors',
 'plot',
 'ready',
 'results',
 'run']

Trying to figure out what this means is a lot more work! For example, from dir(), you would’t know if run is an attribute (is it a flag indicating that the sim was run?) or a method.

In fact, this representation of an object is so useful, you can use it when you create the class. Then if you do print(sim), you’ll get the full representation rather than just the default (class name and memory address):

[6]:
class PrettySim(sc.prettyobj): # This line is key, everything else is the same as before!
    def __init__(self, n=10, n_factors=5):
        self.n = n
        self.n_factors = n_factors
        self.results = sc.objdict()
        self.ready = False

    def run(self):
        for i in range(self.n_factors):
            label = f'i={i+1}'
            result = np.random.randint(0, 10, self.n)**(i+1)
            self.results[label] = result
        self.ready = True

    def plot(self):
        plt.plot(self.results[:])

sim = PrettySim()
sim.run()
print(sim)
<__main__.PrettySim at 0x7ff9d7b55490>
[<class '__main__.PrettySim'>, <class 'sciris.sc_printing.prettyobj'>]
————————————————————————————————————————————————————————————————————————
Methods:
  plot()                  run()
————————————————————————————————————————————————————————————————————————
        n: 10
n_factors: 5
    ready: True
  results: #0. 'i=1': array([7, 8, 8, 5, 5, 6, 3, 4, 7, 5])
           #1. 'i=2': array([49,  [...]
————————————————————————————————————————————————————————————————————————

(Some readers may question whether this representation is more useful than it is pretty. Point taken.)

Monitoring progress#

What if you have a really slow task and you want to check progress? You can use sc.progressbar for that, which builds on the excellent package tqdm:

[7]:
class SlowSim(PrettySim):

    def run_slow(self):
        for i in sc.progressbar(range(self.n_factors)): # This is the only change!
            sc.randsleep(0.2) # Make it slow
            label = f'i={i+1}'
            result = np.random.randint(0, 10, self.n)**(i+1)
            self.results[label] = result
        self.ready = True

slowsim = SlowSim()
slowsim.run_slow()
100%|██████████| 5/5 [00:00<00:00,  7.12it/s]

Note that the progress bar looks better in a regular terminal than in Jupyter, and needless to say, it doesn’t look like anything in a static web page!