Google Collab How to show value of assignments? - python

I am working on this python notebook in Google Collab:
https://github.com/AllenDowney/ModSimPy/blob/master/notebooks/chap01.ipynb
I had to change the configuration line because the one stated in the original was erroring out:
# Configure Jupyter to display the assigned value after an assignment
# Line commented below because errors out
# %config InteractiveShell.ast_node_interactivity='last_expr_or_assign'
# Edit solution given below
%config InteractiveShell.ast_node_interactivity='last_expr'
However, I think the original statement was meant to show values of assignments (if I'm not mistaken), so that when I run the following cell in the notebook, I should see an output:
meter = UNITS.meter
second = UNITS.second
a = 9.8 * meter / second**2
If so how can I make the notebook on google collab show output of assignments?

The short answer is: you can not show output of assignments in Colab.
Your confusion comes from how Google Colab works. The original script is meant to run in IPython. But Colab is not a regular IPython. When you run IPython shell, your %config InteractiveShell.ast_node_interactivity options are (citing documentation)
‘all’, ‘last’, ‘last_expr’ , ‘last_expr_or_assign’ or ‘none’,
specifying which nodes should be run interactively (displaying output
from expressions). ‘last_expr’ will run the last node interactively
only if it is an expression (i.e. expressions in loops or other blocks
are not displayed) ‘last_expr_or_assign’ will run the last expression
or the last assignment. Other values for this parameter will raise a
ValueError.
all will display all the variables, but not the assignments, for example
x = 5
x
y = 7
y
Out[]:
5
7
The differences between the options become more significant when you want to display variables in the loop.
In Colab your options are restricted to ['all', 'last', 'last_expr', 'none']. If you select all, the result for the above cell will be
Out[]:
57
Summarizing all that, there is no way of showing the result of assignment in Colab. Your only option (AFAIK) is to add the variable you want to see to the cell where it is assigned (which is similar to regular print):
meter = UNITS.meter
second = UNITS.second
a = 9.8 * meter / second**2
a

Google Colab has not yet been upgraded to the latest IPython version- if you explicitly upgrade with
!pip install -U ipython
then last_expr_or_assign will work.

Well the easy way is to just wrap your values in print statements like:
print(meter)
print(second)
print(a)
However, if you want to do it the jupyter way, looks like the answer is
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
Found the above from this link: https://stackoverflow.com/a/36835741/7086982

As mentioned by others, it doesn't work as last_expr_or_assign was introduced in juptyer v6.1, and colab is using v5.x. Upgrading the jupyter version on colab might cause some instability (warning shown by colab):
WARNING: Upgrading ipython, ipykernel, tornado, prompt-toolkit or pyzmq can
cause your runtime to repeatedly crash or behave in unexpected ways and is not
recommended
One other solution is to use an extension such as ipydex, which provides magic comments (like ##:, ##:T, ##:S) which cause that either the return value or the right hand side of an assignment of a line is displayed.
!pip install ipydex
%load_ext ipydex.displaytools
e.g.
a = 4
c = 5 ##:
output
c := 5
---

Related

manim does not create an output file

If I run
python -m manimlib scene.py ket_bra
My scene renders fine into the interactive viewer, but I don't get any output file, the terminal prints the following
ManimGL v1.6.1
[13:55:48] INFO Using the default configuration file, which you can modify in `c:\users\miika\manim\manimlib\default_config.yml` config.py:323
INFO If you want to create a local configuration file, you can create a file named `custom_config.yml`, or run `manimgl --config` config.py:324
WARNING You may be using Windows platform and have not specified the path of `temporary_storage`, which may cause OSError. So it is recommended to specify the `temporary_storage` in the config file config.py:290
(.yml)
(process:3548): GLib-GIO-WARNING **: 13:55:49.613: Unexpectedly, UWP app `Clipchamp.Clipchamp_2.3.0.0_neutral__yxz26nhyzhsrt' (AUMId `Clipchamp.Clipchamp_yxz26nhyzhsrt!App') supports 46 extensions but has no verbs
If I add the parameter -p to the command then the interactive window remains blank and doesn't render the scene and in no case do I get an output file which is what I'm looking for and the terminal output is the same as before. Also if it's of note the background is grey, even tho it appears to be black in all samples that I can find. I have absolutely no idea what's going on as I can't find anybody else with a similar issue. I'm using windows 10 and v1.6.1 of 3b1b manim. The scene in this case is as follows (though this issue appears regardless of what the scene is)
from manimlib import *
class ket_bra(Scene):
def construct(self):
ket_q0 = Tex(r"|q_0\rangle")
ket_0 = Tex(r"|0\rangle")
ket_1 = Tex(r"|1\rangle")
ket_0_v2 = Tex(r"|0\rangle")
ket_1_v2 = Tex(r"|1\rangle")
ket_0_v3 = Tex(r"""|0\rangle=\begin{pmatrix}
1\\
0
\end{pmatrix}""")
ket_1_v3 = Tex(r"""|1\rangle=\begin{pmatrix}
0\\
1
\end{pmatrix}""")
bra_kets = VGroup(ket_q0, ket_0, ket_1).arrange(RIGHT, buff=1)
v_bra_kets = VGroup(ket_0_v2, ket_1_v2).arrange(RIGHT, buff=1.5)
bra_kets_def = VGroup(ket_0_v3, ket_1_v3).arrange(RIGHT, buff=1.5)
self.play(Write(ket_q0), Write(ket_0), Write(ket_1))
self.wait(0.5)
self.play(FadeOut(ket_q0))
self.play(Transform(ket_0, ket_0_v2), Transform(ket_1, ket_1_v2))
self.wait(1)
self.play(Transform(ket_0, ket_0_v3), Transform(ket_1, ket_1_v3))
Well I fixed the problem, without fixing the problem, I just switched to the community edition of manim and it works exactly as intended, so if you encounter the same problem and you're using 3b1b manim version, I reccomend just switching to the community version of manim, they are mostly functionally equivalent, but the community edition appears to be less buggy at least for me. Here's a super easy installation guide for it https://docs.manim.community/en/stable/installation/windows.html
However, I won't mark this as the best answer, because I didn't really solve the problem, and I still get the following warning and have no idea what it is. However, it appears to not affect functionality so it's fine, lol.
Windows Solution
Create TempLatex directory in C drive
Find manimlib/default_config.yml in the manim (manimgl version) directory and open it with a text editor
Modify line 18: before: temporary_storage: "" after: temporary_storage: "C:/TempLatex "
Save
From:
https://github.com/3b1b/manim/issues/1661#issuecomment-996575974

Is there a way to obtain the same LaTeX output as one gets in Jupyter, but in Visual Studio?

For some unbeknownst reason which I have not been able to identify, and I already proposed in the form of my first programming question, I can not get the results as smoothly as I previously could in Jupyter notebook and the only result is a "Busy Kernel". The same result occurs when the same code is run in Spyder. I was wondering is there a way to produce this result in Visual Studio 2022? Because when I run the Python code integrated with LaTeX in Visual Studio, no observable difference can be seen between print() function and display() function. Here is the code:
x = 7
y = -2
z = 5
ans = 3*x*(4+y)
display(Math( '3x(4+y)=%g' %ans))
display(Math( '3\\times %g(4+%g)=%g' %(x,y,ans)))
ans2 = -y - (x+3)/z
display(Math( '-y-\\frac{x+3}{z}=%g' %ans2 ))
display(Math( '-%g-\\frac{%g+3}{%g}=%g' %(y,x,z,ans2) ))
I recognize that example, because just now I am following the same Udemy course.
For the exercises in the course I am not using Visual Studio, but the Jupyter extension for VS Code, and the output is the nice expected Latex one.
Did you remember to load the display and Math functions before?
from IPython.display import display, Math

Setting a widget input using a variable in Databricks

Like the question says, I want to know if/how you can set a Databricks widget input using a variable instead of a hard-coded value. I have two notebooks. One needs apply a filter to some values. The other needs to run some code, then optionally (as dictated by another widget) apply that same filter.
Here's some example code (modified for simplicity/privacy).
In Notebook2 we have:
start = dbutils.widgets.get("startDate")
filter_condition = None
if start:
filter_condition = f"GeneratedDate >= '{start}'"
foo = important_function(filter_condition)
%run ./Notebook1 $run_training="True" $num_trials=100 $filter_string=filter_condition
where I want filter_condition to be the above-defined variable and not a string.
In Notebook1, there's some code like:
if run_training=="True":
bar = optimize_model(datasets, grid, int(num_trials))
elif run_training=="False":
baz = apply_filter(filter_string)
else:
# Throw error
You're probably looking for the notebook.run function of the databricks utilities package, rather than the %run command:
dbutils.notebook.run(path='./Notebook1',
timeout_seconds=300,
arguments={'run_training':'True',
'num_trials':100,
'filter_string':filter_condition})
The notebook will be run as a "ephemeral" job. Note that the notebook will run in a separate notebook environment, so any variables etc created will not be brought back into the notebook you ran it from. Your input arguments come through as widget variables, which can be accessed using:
num_trails = dbutils.widgets.get('num_trails')
etc. I think you are already doing that though.

Why python doesn't see the members of quantumCircuit class qiskit

I`m trying to learn the programming on quantum computers.
I have installed qiskit in VS Code (all qiskit extentions available in VS Code market) , python compilator (from Vs Code market "Python" and "Python for VSCode"). I have set up my qikit API for correct working
When I run the exemple I get erros: "Instance of 'QuantumCircuit' has no 'h' member"
What shoud I do?
The code:
from qiskit import ClassicalRegister, QuantumRegister
from qiskit import QuantumCircuit, execute
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q)
qc.h(q[0])
qc.cx(q[0], q[1])
qc.measure(q, c)
job_sim = execute(qc, 'local_qasm_simulator')
sim_result = job_sim.result()
print(sim_result.get_counts(qc))
========================
The same error after adding comment # pylint: disable=no-member
The errors in question are coming from pylint, a linter, not from python itself. While pylint is pretty clever, some constructs (particularly those involving dynamically-added properties) are beyond its ability to understand. When you encounter situations like this, the best course of action is twofold:
Check the docs, code, etc. to make absolutely sure the code that you've written is right (i.e. verify that the linter result is a false positive)
Tell the linter that you know what you're doing and it should ignore the false positive
user2357112 took care of the first step in the comments above, demonstrating that the property gets dynamically set by another part of the library.
The second step can be accomplished for pylint by adding a comment after each of the offending lines telling it to turn of that particular check for that particular line:
qc.h(q[0]) # pylint: disable=no-member

Dependency between "Session/line number was not unique in database." error and Python code

For some time I am getting the following error (warning?):
ERROR! Session/line number was not unique in database. History logging moved to new session
when working with Jupyter notebook (<XXXX> is a number, e.g. 9149).
As the same error has been reported for Spyder (Spyder's Warning: "Session/line number not unique in database") my guess is that there is some problem with the IPython kernel logging.
The question is: may there be any relation between running my code and the error?
Is it likely the error is caused by my code? I touch IPython API as following:
import IPython
def beep():
Python.display.display(IPython.display.Audio(url="http://www.w3schools.com/html/horse.ogg", autoplay=True))
def play_sound(self, etype, value, tb, tb_offset=None):
self.showtraceback((etype, value, tb), tb_offset=tb_offset)
beep()
get_ipython().set_custom_exc((Exception,), play_sound)
I use the beep() function in my code. I also work with large data which results in MemoryError exceptions.
And more importantly, may the error affect my code behaviour (given I do not try to access the logs)?
[EDIT]
It seems the issue is different than Spyder's Warning: "Session/line number not unique in database" as I am able to reproduce it with Jupyter Notebook but not with Spyder.
It is only a partial answer - the bounty is still eligible.
The error does depend on my code - at least when there is SyntaxError.
I have reproduced it with three following cells.
In [31]: print(1)
1
In [31]: print 2
File "<ipython-input-32-9d8034018fb9>", line 1
print 2
^
SyntaxError: Missing parentheses in call to 'print'
In [32]: print(2)
2
ERROR! Session/line number was not unique in database. History logging moved to new session 7
As you can see the line counter has been not increased in the second cell (with syntax issues).
Inspired by #zwer's comment, I have queried the $HOME/.ipython/profile_default/history.sqlite database:
sqlite> select session, line, source from history where line > 30;
6|31|print(1)
6|32|print 2
7|32|print(2)
It is clear that the line counter for the second cell has been increased in the database, but not in the notebook.
Thus when the third cell has been executed successfully, the notebook attempted to store its source with the same line, which offended the PRIMARY KEY constraint:
sqlite> .schema history
CREATE TABLE history
(session integer, line integer, source text, source_raw text,
PRIMARY KEY (session, line));
As a result, a failsafe has been triggered which issued the warning and created a new session.
I guess the issue is not affecting my code behaviour, however I miss a credible source for such statement.
I experienced the same error when I was trying to run some asyncio code in a jupyter notebook. The gist was like this (might make sense to those familiar with asyncio)
cell #1
output = loop.run_until_complete(future)
cell #2
print(output)
Run both cells together, and I would get OP's error.
Merge the cells together like so, and it ran cleanly
cell #1
output = loop.run_until_complete(future)
print(output)
This problem arises in the Jupyter Notebook cells when the cells have the same line number.
What you can do - if you are in Jupyter Notebook - is just restart the kernel.
The error will be solved.

Categories

Resources