def interact_with(df, ndims=3, **kwargs):
"""
Interactively view a DataFrame.
Parameters
----------
df : DataFrame
The DataFrame to interact with
ndims : int, optional
The number of dimensions wished to encode at start (the number of rows
with encoding/data/function/data_type).
Notes
-----
In the Jupyter notebook, display a widget to allow you to selectively plot
columns to plot/encode/etc.
Use a smaller value if ndims if less dimensions and controls are desired.
"""
return Interact(df, ndims=ndims, **kwargs)
python类display()的实例源码
def __init__(self, df, ndims=3, show=True):
if not isinstance(df, pd.core.frame.DataFrame):
raise ValueError('Interact takes a DataFrame as input')
columns = [None] + _get_columns(df)
self.columns = columns
encodings = _get_encodings()
self.df = df
encodings = [{'encoding': encoding}
for encoding in encodings[:ndims]]
self.settings = {'mark': {'mark': 'mark_point'},
'encodings': encodings}
self.controller = self._generate_controller(ndims)
self.show = show
if self.show:
display(self.controller)
self.plot(show=show)
def play_sequence(sequence,
synth=midi_synth.synthesize,
sample_rate=_DEFAULT_SAMPLE_RATE,
colab_ephemeral=True,
**synth_args):
"""Creates an interactive player for a synthesized note sequence.
This function should only be called from a Jupyter or Colab notebook.
Args:
sequence: A music_pb2.NoteSequence to synthesize and play.
synth: A synthesis function that takes a sequence and sample rate as input.
sample_rate: The sample rate at which to synthesize.
colab_ephemeral: If set to True, the widget will be ephemeral in Colab, and
disappear on reload (and it won't be counted against realtime document
size).
**synth_args: Additional keyword arguments to pass to the synth function.
"""
array_of_floats = synth(sequence, sample_rate=sample_rate, **synth_args)
try:
import google.colab # pylint: disable=unused-import,unused-variable,g-import-not-at-top
colab_play(array_of_floats, sample_rate, colab_ephemeral)
except ImportError:
display.display(display.Audio(array_of_floats, rate=sample_rate))
def general_description(self):
# General data description:
# Filename:
if self._path_file is None:
file_name = "file with no path"
else:
file_name = self._path_file.split('/')[-1]
# Counting the number of columns:
row_number = self._df.count()
# Counting the number of rows:
col_number = len(self._df.columns)
# Writting General Description table:
temp_obj = GeneralDescripTable(file_name, col_number, row_number)
display(temp_obj)
data_types = len(set([x[1] for x in self._df.dtypes]))
return self._create_dict(["filename", "size", "columns", "rows", "datatypes"],
[file_name, 500, col_number, row_number, data_types])
# Funtion to analize column datatypes, it also plot proportion datatypes and histograms:
geometry_viewer.py 文件源码
项目:notebook-molecular-visualization
作者: Autodesk
项目源码
文件源码
阅读 23
收藏 0
点赞 0
评论 0
def __init__(self, mol, style=None, display=False, width='100%', height='400px',
**kwargs):
kwargs.update(width=width, height=height)
super().__init__(**kwargs)
self.height = in_pixels(height)
self.width = in_pixels(width)
self.atom_colors = {}
# current state
self.atom_highlights = []
self._axis_objects = None
self._colored_as = {}
self.add_molecule(mol)
if style is None:
self.autostyle()
else:
self.set_style(style)
if display:
dsp.display(self)
geometry_viewer.py 文件源码
项目:notebook-molecular-visualization
作者: Autodesk
项目源码
文件源码
阅读 22
收藏 0
点赞 0
评论 0
def set_positions(self, positions=None):
""" Set positions of atoms in the 3D display
Args:
positions (Matrix[length, shape=(*,3)]): positions to set atoms to - optional.
If not provided, positions are taken from current positions of the molecule.
Returns:
"""
if positions is None:
pos = self.mol.positions
else:
pos = positions
self.positions = pos.value_in(u.angstrom).tolist()
self._update_clipping(np.abs(pos.value_in(self.DISTANCE_UNITS)).max())
def make_movie(line, cell=None):
toks = shlex.split(line)
skip = 0
publish = False
display_id = None
caption = None
cptr = None;
for i in range(len(toks)):
if skip > 0:
skip = skip-1
continue
tok = toks[i]
if tok == "-publish":
publish = True
elif tok == "-caption":
skip = 1
caption = toks[i+1]
elif tok == "-capture":
skip = 1
cptr = toks[i+1]
elif tok == "-display":
skip = 1
display_id = toks[i+1]
return Idv.make_movie(publish, caption, display_id=display_id, capture=cptr)
def view_url_clicked(b):
DrilsdownUI.do_display(HTML("<a target=ramadda href=" + b.url + ">" + b.name + "</a>"))
display(IFrame(src=b.url, width=800, height=400))
def publish_notebook(extra=None):
# If we do this then the Javascript object shows up in the notebook
# js = Javascript('IPython.notebook.save_checkpoint();')
# display(js)
file = Idv.getname()
if file is None:
return
isl = '<isl><publish file="' + file + '"/></isl>'
DrilsdownUI.status("Make sure you do 'File->Save and Checkpoint'. Check your IDV to publish the file")
result = Idv.run_isl(isl);
if not result.ok():
print("Publication failed")
return
if result.get_results().strip()!="":
print("Publication successful")
print("URL: " + result.get_results())
return
print("Publication failed")
def export_data(filename=None, display_id=None, load_data = False):
DrilsdownUI.status("Exporting data ...")
extra = ""
if display_id is not None:
extra += ' display="' + display_id + '" '
if filename is None:
f = NamedTemporaryFile(suffix='.gif', delete=False)
filename = f.name;
isl = '<isl><export file="' + f.name + '"' \
+ extra + '/></isl>'
result = Idv.run_isl(isl)
if not result.ok():
return;
if load_data:
placeholder = false;
# return load_data(filename);
# img = '<img src="data:image/gif;base64,{0}">'
DrilsdownUI.status("data exported to: " + filename)
def do_list(self, dir=None, display=False, label="Entries"):
"""make a list of RamaddaEntry objects that are children of the given entryId"""
if dir is None:
dir = self.dir
files = os.listdir(dir)
entries = []
prefix = dir+"/"
if prefix == "./":
prefix = ""
for i in range(len(files)):
if files[i].startswith(".") is not True:
entries.append(FileEntry(self, prefix + files[i]))
if display:
self.display_entries(label, entries)
else:
return entries
def update_display(obj, *, display_id, **kwargs):
"""Update an existing display by id
Parameters
----------
obj:
The object with which to update the display
display_id: keyword-only
The id of the display to update
See Also
--------
:func:`display`
"""
kwargs['update'] = True
display(obj, display_id=display_id, **kwargs)
def display_markdown(*objs, **kwargs):
"""Displays the Markdown representation of an object.
Parameters
----------
objs : tuple of objects
The Python objects to display, or if raw=True raw markdown data to
display.
raw : bool
Are the data objects raw data or Python objects that need to be
formatted before display? [default: False]
metadata : dict (optional)
Metadata to be associated with the specific mimetype output.
"""
_display_mimetype('text/markdown', objs, **kwargs)
def display_pdf(*objs, **kwargs):
"""Display the PDF representation of an object.
Parameters
----------
objs : tuple of objects
The Python objects to display, or if raw=True raw javascript data to
display.
raw : bool
Are the data objects raw data or Python objects that need to be
formatted before display? [default: False]
metadata : dict (optional)
Metadata to be associated with the specific mimetype output.
"""
_display_mimetype('application/pdf', objs, **kwargs)
#-----------------------------------------------------------------------------
# Smart classes
#-----------------------------------------------------------------------------
def __init__(self, data=None, url=None, filename=None, expanded=False, metadata=None, **kwargs):
"""Create a JSON display object given raw data.
Parameters
----------
data : dict or list
JSON data to display. Not an already-serialized JSON string.
Scalar types (None, number, string) are not allowed, only dict
or list containers.
url : unicode
A URL to download the data from.
filename : unicode
Path to a local file to load the data from.
expanded : boolean
Metadata to control whether a JSON display component is expanded.
metadata: dict
Specify extra metadata to attach to the json display object.
"""
self.metadata = {'expanded': expanded}
if metadata:
self.metadata.update(metadata)
if kwargs:
self.metadata.update(kwargs)
super(JSON, self).__init__(data=data, url=url, filename=filename)
def displayResult(self):
fig = plt.figure(101)
plt.subplot(221)
plt.imshow(np.abs(self.reconstruction),origin='lower')
plt.draw()
plt.title('Reconstruction Magnitude')
plt.subplot(222)
plt.imshow(np.angle(self.reconstruction),origin='lower')
plt.draw()
plt.title('Reconstruction Phase')
plt.subplot(223)
plt.imshow(np.abs(self.aperture),origin='lower')
plt.title("Aperture Magnitude")
plt.draw()
plt.subplot(224)
plt.imshow(np.angle(self.aperture),origin='lower')
plt.title("Aperture Phase")
plt.draw()
fig.canvas.draw()
#fig.tight_layout()
# display.display(fig)
# display.clear_output(wait=True)
# time.sleep(.00001)
def run_next_cells(n):
if n=='all':
n = 'NaN'
elif n<1:
return
js_code = """
var num = {0};
var run = false;
var current = $(this)[0];
$.each(IPython.notebook.get_cells(), function (idx, cell) {{
if ((cell.output_area === current) && !run) {{
run = true;
}} else if ((cell.cell_type == 'code') && !(num < 1) && run) {{
cell.execute();
num = num - 1;
}}
}});
""".format(n)
display(Javascript(js_code))
def make_legend(title,colors,labels):
colorhashs=[]
for row in colors:
colorhashs.append(get_colors(row))
return '''
<div id='legend' style='display:none;'>
<strong>%s</strong>
<nav class='legend clearfix'>
<span style='background:%s;'></span>
<span style='background:%s;'></span>
<span style='background:%s;'></span>
<span style='background:%s;'></span>
<span style='background:%s;'></span>
<label>%s</label>
<label>%s</label>
<label>%s</label>
<label>%s</label>
<label>%s</label>
<small>Source: <a href="https://github.com/murphy214/berrl">Made using Berrl</a></small>
</div>
''' % (title,colorhashs[0],colorhashs[1],colorhashs[2],colorhashs[3],colorhashs[4],labels[0],labels[1],labels[2],labels[3],labels[4])
# returns the blocks of color backgrounds for a given list of colors
def make_top2(rangelist):
widthpercentage = 100.0 / float(len(rangelist))
return '''<style>
.legend label,
.legend span {
display:block;
float:left;
height:15px;
width:xx%;
text-align:center;
font-size:9px;
color:#808080;
}
</style>'''.replace('xx',str(widthpercentage))
# generates 5 labels and then inserts dummy spaces in each label value not used
# may eventually accept a number of labels right now assumes 5 and returns adequate dummy labels for inbetween values
def make_top2(rangelist):
widthpercentage = 100.0 / float(len(rangelist))
return '''<style>
.legend label,
.legend span {
display:block;
float:left;
height:15px;
width:xx%;
text-align:center;
font-size:9px;
color:#808080;
}
</style>'''.replace('xx',str(widthpercentage))
# generates 5 labels and then inserts dummy spaces in each label value not used
# may eventually accept a number of labels right now assumes 5 and returns adequate dummy labels for inbetween values
def show(self):
r"""This will send any existing plots to the IPython notebook.
If yt is being run from within an IPython session, and it is able to
determine this, this function will send any existing plots to the
notebook for display.
If yt can't determine if it's inside an IPython session, it will raise
YTNotInsideNotebook.
Examples
--------
>>> import yt
>>> ds = yt.load('IsolatedGalaxy/galaxy0030/galaxy0030')
>>> pp = ProfilePlot(ds.all_data(), 'density', 'temperature')
>>> pp.show()
"""
if "__IPYTHON__" in dir(builtins):
from IPython.display import display
display(self)
else:
raise YTNotInsideNotebook
def _repr_html_(self):
"""Return an html representation of the plot object. Will display as a
png for each WindowPlotMPL instance in self.plots"""
ret = ''
unique = set(self.plots.values())
if len(unique) < len(self.plots):
iters = izip(range(len(unique)), sorted(unique))
else:
iters = iteritems(self.plots)
for uid, plot in iters:
with matplotlib_style_context():
img = plot._repr_png_()
img = base64.b64encode(img).decode()
ret += r'<img style="max-width:100%%;max-height:100%%;" ' \
r'src="data:image/png;base64,{0}"><br>'.format(img)
return ret
def __init__(self, mode = 'whole sphere', resolution = (45, 90) ):
"mode = 'whole sphere' | 'spherical blackboard'"
self.mode = mode
if self.mode == 'whole sphere' :
thetas = linspace(0, pi, resolution[0] + 1)
phis = linspace(-pi, pi, resolution[1] + 1)
elif self.mode == 'spherical blackboard' :
thetas = linspace(0,.5*pi, resolution[0] + 1)
phis = linspace(-pi/3, 0, resolution[1] + 1)
(self.theta_grid, self.phi_grid) = meshgrid(thetas, phis)
self.theta_centers = (self.theta_grid[0:-1,0:-1] + self.theta_grid[0:-1,1:] + self.theta_grid[1:,0:-1] + self.theta_grid[1:,1:]) / 4.
self.phi_centers = (self.phi_grid[0:-1,0:-1] + self.phi_grid[0:-1,1:] + self.phi_grid[1:,0:-1] + self.phi_grid[1:,1:] ) / 4.
areas_thetas = (phis[1]-phis[0]) * ( -cos(thetas[1:]) + cos(thetas[0:-1]))
self.cell_areas = vstack( (areas_thetas,)*(resolution[1]) ).T
# Setup routines for the interactive "Plot.ly" display
self.setup_layout()
self.current_axis = []
def plot_image(image):
# Assume the pixel-values are scaled between 0 and 255.
if False:
# Convert the pixel-values to the range between 0.0 and 1.0
image = np.clip(image/255.0, 0.0, 1.0)
# Plot using matplotlib.
plt.imshow(image, interpolation='lanczos')
plt.show()
else:
# Ensure the pixel-values are between 0 and 255.
image = np.clip(image, 0.0, 255.0)
# Convert pixels to bytes.
image = image.astype(np.uint8)
# Convert to a PIL-image and display it.
display(PIL.Image.fromarray(image))
# Normalize an image so its values are between 0.0 and 1.0. This is useful for plotting the gradient.
# In[13]:
def __init__(self, spec=None, data=None, url=None, filename=None, metadata=None):
"""Create a VegaLite display object given raw data.
Parameters
----------
spec : dict
VegaLite spec. Not an already-serialized JSON string.
data : dict or list
VegaLite data. Not an already-serialized JSON string.
Scalar types (None, number, string) are not allowed, only dict
or list containers.
url : unicode
A URL to download the data from.
filename : unicode
Path to a local file to load the data from.
metadata: dict
Specify extra metadata to attach to the json display object.
"""
super(VegaLite, self).__init__(spec=spec, data=data, url=url, filename=filename)
def __init__(self, spec=None, data=None, url=None, filename=None, metadata=None):
"""Create a VegaLite display object given raw data.
Parameters
----------
spec : dict
VegaLite spec. Not an already-serialized JSON string.
data : dict or list
VegaLite data. Not an already-serialized JSON string.
Scalar types (None, number, string) are not allowed, only dict
or list containers.
url : unicode
A URL to download the data from.
filename : unicode
Path to a local file to load the data from.
metadata: dict
Specify extra metadata to attach to the json display object.
"""
super(VegaLite, self).__init__(spec=spec, data=data, url=url, filename=filename)
def show_site(self, article, nwork, info):
"""Display site citation"""
text = "# Temp\n"
text += "insert('''"
text += citation_text(
self.citation_var, info,
ref=article.get('citation_id', ''),
backward=self.backward
) + "\n"
text += "''', citations='{}');".format(self.citation_file)
display_cell(text)
self.output_widget.clear_output()
with self.output_widget:
if self.to_display:
display("\n".join(self.to_display))
if 'div' in article:
display(HTML(repr(article['div'])))
elif 'name' in article:
print(article['name'])
self.to_display = []
def update_r_widget(self, *args):
"""Callback for updating r_widget value"""
self._display_stack += 1
r_value = self.r_widget.value
dist_min = 2 * r_value + 2
letters_max = int(r_value / 3.6)
self.margin_left_widget.min = -1
self.margin_left_widget.value = max(r_value, self.margin_left_widget.value)
self.margin_left_widget.min = r_value
self.dist_x_widget.min = -1
self.dist_x_widget.value = max(dist_min, self.dist_x_widget.value)
self.dist_x_widget.min = dist_min
self.dist_y_widget.min = -1
self.dist_y_widget.value = max(dist_min, self.dist_y_widget.value)
self.dist_y_widget.min = dist_min
self.letters_widget.max = 5000
self.letters_widget.value = min(letters_max, self.letters_widget.value)
self.letters_widget.max = letters_max
self.display()
def create_category(self, name, attr, value, color, font_color):
"""Create category widget"""
VIS = ['none', '']
widget = self.toggle_widgets[attr] = ToggleButton(value=value, description=name)
wcolor = self.color_widgets[attr] = ColorPicker(value=color, description=name, width="180px")
wfont_color = self.font_color_widgets[attr] = ColorPicker(value=font_color, width="110px")
def visibility(*args):
"""" Toggles visibility of category """
self._display_stack += 1
wcolor.layout.display = VIS[int(widget.value)]
wfont_color.layout.display = VIS[int(widget.value)]
self.display()
widget.observe(visibility, "value")
wcolor.observe(self.update_widget, "value")
wfont_color.observe(self.update_widget, "value")
visibility()
def ka_display_muti_tables_summary(tables, table_names, n=5):
'''display multi tables' summary
Parameters
----------
tables: list_like
Pandas dataframes
table_names: list_like
names of each dataframe
Return
------
1. show head of data
2. show column types of data
3. show summary of data
'''
for t, t_name in zip(tables, table_names):
print(t_name + ":", t.shape)
ka_display_side_by_side(t.head(n=n), _ka_display_col_type(t), DataFrameSummary(t).summary())