Bokeh: Models must be owned by only a single document - bokeh

I'm working with Bokeh 0.12.2 in a Jupyter notebook and it frequently throws exceptions about "Models must be owned by only a single document":
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-23-f50ac7abda5e> in <module>()
2 ea.legend.label_text_font_size = '10pt'
3
----> 4 show(column([co2, co, nox, o3]))
C:\Users\pokeeffe\AppData\Local\Continuum\Anaconda3\lib\site-packages\bokeh\io.py in show(obj, browser, new, notebook_handle)
308 '''
309 if obj not in _state.document.roots:
--> 310 _state.document.add_root(obj)
311 return _show_with_state(obj, _state, browser, new, notebook_handle=notebook_handle)
312
C:\Users\pokeeffe\AppData\Local\Continuum\Anaconda3\lib\site-packages\bokeh\document.py in add_root(self, model)
443 self._roots.append(model)
444 finally:
--> 445 self._pop_all_models_freeze()
446 self._trigger_on_change(RootAddedEvent(self, model))
447
C:\Users\pokeeffe\AppData\Local\Continuum\Anaconda3\lib\site-packages\bokeh\document.py in _pop_all_models_freeze(self)
343 self._all_models_freeze_count -= 1
344 if self._all_models_freeze_count == 0:
--> 345 self._recompute_all_models()
346
347 def _invalidate_all_models(self):
C:\Users\pokeeffe\AppData\Local\Continuum\Anaconda3\lib\site-packages\bokeh\document.py in _recompute_all_models(self)
367 d._detach_document()
368 for a in to_attach:
--> 369 a._attach_document(self)
370 self._all_models = recomputed
371 self._all_models_by_name = recomputed_by_name
C:\Users\pokeeffe\AppData\Local\Continuum\Anaconda3\lib\site-packages\bokeh\model.py in _attach_document(self, doc)
89 '''This should only be called by the Document implementation to set the document field'''
90 if self._document is not None and self._document is not doc:
---> 91 raise RuntimeError("Models must be owned by only a single document, %r is already in a doc" % (self))
92 doc.theme.apply_to_model(self)
93 self._document = doc
RuntimeError: Models must be owned by only a single document, <bokeh.models.tickers.DaysTicker object at 0x00000000042540B8> is already in a doc
The trigger is always calling show(...) (although never the first time after kernel start-up, only subsequent calls).
Based on the docs, I thought reset_output() would return my notebook to an operable state but the exception persists. Through trial-and-error, I've determined it's necessary to also re-define everything being passing to show(). That makes interactive work cumbersome and error-prone.
[Ref]:
reset_output(state=None)
  Clear the default state of all output modes.
  Returns: None
Am I right about reset_output() -- is it supposed to resolve the situation causing this exception?
Else, how do I avoid this kind of exception?

It may be because of conflicting objects that has the same name. you need to create completely new objects every time.

Seems it can by fixed by differentiating the source name
Like this:
source1 = df
p1.circle('A', 'B', source=source1)
source2 = df
p2 = figure()
p2.circle('C', 'D', source=source2)
sourceN = df
p2 = figure()
p2.circle('X', 'Y', source=sourceN)

I've been working in a jupyterlab notebook iterating on visualizations of a large amount of data with bokeh, holoviews, and panel, and have been running into this issue periodically.
Here are a couple of additional things that may help. Note that p is used as the bokeh conventional name for the figure. I am posting on this old thread because it was the top result in my Google search for the error message.
Try clearing the document (found in docs):
from bokeh.io import curdoc
curdoc().clear()
I observed that panel was able to display a bokeh object even when bokeh show would not.
import panel as pn
pn.extension()
pn.pane.Bokeh(p)
Digging into how panel is able to display an object even when bokeh is not, I noticed this function, which fixed the problem for me:
import panel as pn
pn.io.model.remove_root(p)
If you don't have panel installed, here is the source code from above:
from bokeh.models import Model
for model in p.select({'type': Model}):
prev_doc = model.document
model._document = None
if prev_doc:
prev_doc.remove_root(model)
Hopefully this helps someone, or future me.

I ran into this error message when using file_html from from bokeh.embed, after i upgraded to bokeh version 1.01. Downgrading again to bokeh version 0.12.16 solved it. (pip install bokeh==0.12.16)
Note sure why.

This solution works without upgrading or downgrading packages.
try:
reset_output()
output_notebook()
show(p)
except:
output_notebook()
show(p)
Solution provided here :
https://github.com/bokeh/bokeh/issues/8579

Try using after creating each plot. add_root will add that model as a root of the current Document, making sure that each Model is added to a single Document:
curdoc().add_root(column([plot]))
curdoc().title = doc_title //Add a title to the doc
show(figure)
Note: column(the list of plots) can be replaced with any object which inherits the Model class.
Refer to the link for more details on add_root and bokeh Documents: https://docs.bokeh.org/en/latest/docs/reference/document.html?highlight=add_root#bokeh.document.document.Document.add_root

column_data_source = ColumnDataSource(dataframe)
After each row in the jupyter notebook that used the column data source we have to make it again simply. The column data source seems like we cant use it many times in the same code.
This seems a little hack but it worked for me when i faced the same error.

Related

Reset the function wrongly assigned as string in python using Jupyter

I was practicing plotting when by mistake I assigned ylabel and title as below:
plt.ylabel = "No. of Hospitals"
plt.title = 'Hospitals by State'
This changed the two functions to string, as confirmed in the image below. (First blue circle)
Then I changed the statement to set these correctly to:
plt.ylabel("No. of Hospitals")
plt.title('Hospitals by State')
Now, I get the error
TypeError: 'str' object is not callable
In one of the stackoverflow article, I learned once the function is wrongly assigned then only way to fix this is restart the kernel. I don't want to restart the kernel and run all 500+ jobs above this mistake. I also tried importing matplotlib and sns again by calling pyplot as plt2 that didn't work either. (Second Blue circle in the image).
I was wondering is there a way to reset the function back to normal from the string status now?
I do understand that I can write the dataframe of interest to a file and then read it back in the new notebook. However, I'm sure many will agree knowing the process and ability to reset the function back to normal will help many in future without costly work around(s).
You may redefine them, like:
plt.title = lambda *args, **kwargs: plt.gca().set_title(*args, **kwargs)
plt.ylabel = lambda *args, **kwargs: plt.gca().set_ylabel(*args, **kwargs)
See also the original code of matplotlib.pyplot.title and matplotlib.pyplot.ylabel.

How to avoid RuntimeError while call __dict__ on module?

it is appearing in some big modules like matplotlib. For example expression :
import importlib
obj = importlib.import_module('matplotlib')
obj_entries = obj.__dict__
Between runs len of obj_entries can vary. From 108 to 157 (expected) entries. Especially pyplot can be ignored like some another submodules.
it can work stable during manual debug mode with len computing statement after dict extraction. But in auto it dont work well.
such error occures:
RuntimeError: dictionary changed size during iteration
python-BaseException
using clear python 3.10 on windows. Version swap change nothing at all
during some attempts some interesting features was found.
use of repr is helpfull before dict initiation.
But if module transported between classes like variable more likely lazy-import happening? For now there is evidence that not all names showing when command line interpriter doing opposite - returning what expected. So this junk of code help bypass this bechavior...
Note: using pkgutil.iter_modules(some_path) to observe modules im internal for pkgutil ModuleInfo form.
import pkgutil, importlib
module_info : pkgutil.ModuleInfo
name = module_info.name
founder = module_info.module_finder
spec = founder.find_spec(name)
module_obj = importlib.util.module_from_spec(spec)
loader = module_obj.__loader__
loader.exec_module(module_obj)
still unfamilliar with interior of import mechanics so it will be helpfull to recive some links to more detail explanation (spot on)

AttributeError: 'dict' object has no attribute 'to'

I used an example of using BERT to classify reviews, described at the link. The code is written for using the CPU and it works fine, but slowly. In Colab Google, with a multilingual model, one epoch is considered 4 hours for me. If I replace the CPU with the CUDA everywhere in the code, then the error that YOU met with appears. I followed the guidelines given in the link, but then another error appears:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-3-0b35a5f74768> in <module>()
268 'labels': batch[2],
269 }
--> 270 inputs.to(device)
271 outputs = model(**inputs)
272
AttributeError: 'dict' object has no attribute 'to'
Firstly you do not need to replace the CPU with the CUDA everywhere in the code.
You should just add the following to the cell from which you import the libraries
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
By printing the device object, you can see the gpu that google colab assigned to you to use.
Coming to your question, I think instead of giving the dictionary itself, you just need to give values corresponding to the expected keys.

How can I interact with the Github API using Perl6?

I want to use the Github API in a script and I want to use it as an experience to get better using Perl6. However, I cannot even get a simple proof of concept to work.
Through some testing I realized that Github requires that you supply a valid user agent so I turned to HTTP::UserAgent. No matter what I try, I get the following error:
Internal Error: 'server returned no data'
in block at /Applications/Rakudo/share/perl6/site/sources/FD28A8E22DFE16B70B757D9981C7B6C25543060C (HTTP::UserAgent) line 259
in any at /Applications/Rakudo/share/perl6/site/precomp/F91BAB44DF15C5C298C627DD5E0F9D819ED79939.1517344679.60204/FD/FD28A8E22DFE16B70B757D9981C7B6C25543060C line 1
in method new at /Applications/Rakudo/share/perl6/site/sources/DDDD4497B34FC81BC1F5FF467999BC4DA2FA1CEB (HTTP::Response) line 25
in method get-response at /Applications/Rakudo/share/perl6/site/sources/FD28A8E22DFE16B70B757D9981C7B6C25543060C (HTTP::UserAgent) line 291
in method request at /Applications/Rakudo/share/perl6/site/sources/FD28A8E22DFE16B70B757D9981C7B6C25543060C (HTTP::UserAgent) line 159
in method get at /Applications/Rakudo/share/perl6/site/sources/FD28A8E22DFE16B70B757D9981C7B6C25543060C (HTTP::UserAgent) line 102
in method get at /Applications/Rakudo/share/perl6/site/sources/FD28A8E22DFE16B70B757D9981C7B6C25543060C (HTTP::UserAgent) line 105
in block <unit> at reporter.pl6 line 12
There is even an example in the the repo that doesn't seem to work for me.
#!/usr/bin/env perl6
use v6;
use HTTP::UserAgent;
my $ua = HTTP::UserAgent.new;
$ua.timeout = 1;
my $response = $ua.get('https://github.com');
if $response.is-success {
say $response.content;
} else {
die $response.status-line;
}
Any tips on how to connect to Github via Perl 6? I really love many aspects of the language but this type of thing is discouraging.
EDIT: I went on #perl6 irc and no one was able to reproduce this on other OSes. I got it to work on Debian. The issue seems to be with OS X
Although in alpha stage, WebServices::GitHub is perfectly serviceable. You can use it to download user information, or you can use my fork if you want to interact with issues. This program, for instance, is used to download some issues from a particular repo.

R: How can I disable truncation of listing of package functions?

How can I list all of the results that used to occur when typing packageName<tab>, i.e. the full list offered via auto-completion? In R 2.15.0, I get the following for Matrix::<tab>:
> library(Matrix)
> Matrix::
Matrix::.__C__abIndex Matrix::.__C__atomicVector Matrix::.__C__BunchKaufman Matrix::.__C__CHMfactor Matrix::.__C__CHMsimpl
Matrix::.__C__CHMsuper Matrix::.__C__Cholesky Matrix::.__C__CholeskyFactorization Matrix::.__C__compMatrix Matrix::.__C__corMatrix
Matrix::.__C__CsparseMatrix Matrix::.__C__dCHMsimpl Matrix::.__C__dCHMsuper Matrix::.__C__ddenseMatrix Matrix::.__C__ddiMatrix
Matrix::.__C__denseLU Matrix::.__C__denseMatrix Matrix::.__C__dgCMatrix Matrix::.__C__dgeMatrix Matrix::.__C__dgRMatrix
Matrix::.__C__dgTMatrix Matrix::.__C__diagonalMatrix Matrix::.__C__dMatrix Matrix::.__C__dpoMatrix Matrix::.__C__dppMatrix
Matrix::.__C__dsCMatrix Matrix::.__C__dsparseMatrix Matrix::.__C__dsparseVector Matrix::.__C__dspMatrix Matrix::.__C__dsRMatrix
Matrix::.__C__dsTMatrix Matrix::.__C__dsyMatrix Matrix::.__C__dtCMatrix Matrix::.__C__dtpMatrix Matrix::.__C__dtrMatrix
Matrix::.__C__dtRMatrix Matrix::.__C__dtTMatrix Matrix::.__C__generalMatrix Matrix::.__C__iMatrix Matrix::.__C__index
Matrix::.__C__isparseVector Matrix::.__C__ldenseMatrix Matrix::.__C__ldiMatrix Matrix::.__C__lgCMatrix Matrix::.__C__lgeMatrix
Matrix::.__C__lgRMatrix Matrix::.__C__lgTMatrix Matrix::.__C__lMatrix Matrix::.__C__lsCMatrix Matrix::.__C__lsparseMatrix
[...truncated]
That [...truncated] message is irritating and I want to produce the full listing. Which option/flag/knob/configuration/incantation do I need to invoke in order to avoid the truncation? I have this impression that I used to see the full list, but not anymore - perhaps that was on a different OS (e.g. Linux).
I know that ls("package:Matrix") is one useful approach, but it is not the same as setting an option, and the list is different.
Unfortunately, on Windows, it looks like this behavior is hard-wired into the C code used to construct the console. So the answer seems to be that "no, you can't disable it" (at least not without modifying the sources and then recompiling R from scratch).
Here are the relevant lines from $RHOME/src/gnuwin32/console.c:
909 static void performCompletion(control c)
910 {
911 ConsoleData p = getdata(c);
912 int i, alen, alen2, max_show = 10, cursor_position = p->c - prompt_wid;
...
...
1001 if (alen > max_show)
1002 consolewrites(c, "\n[...truncated]\n");
You are correct that on some other platforms, all of the results are printed out. (I often use Emacs, for instance, and it pops all results of tab completion up in a separate buffer).
As an interesting side note, rcompgen, the backend that actually performs the tab-completion (as opposed to printing results to the console) does always find all completions. It's just that Windows doesn't then print them out for us to see.
You can verify that this happens even on Windows by typing:
library(Matrix)
Matrix::
## Then type <TAB> <TAB>
## Then type <RET>
rc.status() ## Careful not to use tab-completion to complete rc.status !
matches <- rc.status()$comps
length(matches) # -> 288
matches # -> lots of symbols starting with 'Matrix::'
For more details about about the backend, and the functions and options that control its behavior, see ?rcompgen.

Resources