In [6]:
%matplotlib notebook
import matplotlib.pyplot as plt
import hyperspy.api as hs
import matplotlib.pylab as pylab
pylab.rcParams['figure.figsize'] = 8, 6  # that's default image size for this interactive session
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))
#from ipywidgets.widgets import interactive, fixed, interact
from skimage.exposure import equalize_hist, equalize_adapthist, rescale_intensity
from skimage import filters

import os

StackName = 'Stack.bcf'
BinningFactor = 1

def MakeRGBFromMaps(R,G,B, bits=16, equalize=False, cutnoise=False):
    MaxPixelVal = (2**bits)-1
    
    # Make a Signal2D from the three images and copy over the metadata.
    x = hs.stack([R,G,B])
    x = hs.signals.Signal2D(x).T
    x.metadata = R.metadata
    x.original_metadata = R.original_metadata
    x.metadata.General.title = R.metadata.Sample.xray_lines[0] + '(R) ' + G.metadata.Sample.xray_lines[0] + '(G) ' + B.metadata.Sample.xray_lines[0] + '(B)'
    
    rdata = x.data[:,:,0]
    gdata = x.data[:,:,1]
    bdata = x.data[:,:,2]
            
    if cutnoise==True:
        NoiseCutAggressiveness = 1 # 0 means no cut, 1 means full cut.
        rdata[rdata < filters.threshold_triangle(rdata)*NoiseCutAggressiveness] = 0
        gdata[gdata < filters.threshold_triangle(gdata)*NoiseCutAggressiveness] = 0
        bdata[bdata < filters.threshold_triangle(bdata)*NoiseCutAggressiveness] = 0
 
    if equalize==True:
        rdata = equalize_hist(rdata)
        gdata = equalize_hist(gdata)
        bdata = equalize_hist(bdata)

    rdata = rescale_intensity(rdata)*MaxPixelVal
    gdata = rescale_intensity(gdata)*MaxPixelVal
    bdata = rescale_intensity(bdata)*MaxPixelVal

    x.data[:,:,0] = rdata
    x.data[:,:,1] = gdata
    x.data[:,:,2] = bdata

    # Convert to RGB.
    if bits==16:
        x.change_dtype('uint16')
        x.change_dtype('rgb16')
    else:
        x.change_dtype('uint8')
        x.change_dtype('rgb8')    
    
    # Copy the axes info over from the R map.
    x.axes_manager = R.axes_manager.copy()

    return(x)

def EqualizeAxis(fignum=None):
    # Because of a bug in Hyperspi, I sometimes have to set the axis to equal after we rebin.
    if fignum == None:
        fig=plt.gcf()
    else:
        fig = plt.figure(fignum)
    ax = fig.axes
    if type(ax) != list:
        ax.axis('equal')
    else:
        for a in ax:
            a.axis('equal')
    fig.tight_layout()
    
def RemovePtGaContamination(ElementDict):
    '''Make maps without contamination from Pt and Ga in FIB sections.
    The maps in ElementDict must contain Pt and Ga maps (obviously...)
    '''
    ElementDictNoPtGa = dict()
    for ElName, ElMap in ElementDict.items():
        if ElName in ['Pt', 'Ga']:
            ElementDictNoPtGa[ElName] = ElementDict[ElName].deepcopy()
            continue
        ReducedData = ElementDict[ElName].data.astype(float) - ElementDict['Pt'].data.astype(float) - ElementDict['Ga'].data.astype(float)
        ReducedData[ReducedData < 0] = 0
        ReducedElMap = ElMap.deepcopy()
        ReducedElMap.data = ReducedData
        ElementDictNoPtGa[ElName] = ReducedElMap
    return ElementDictNoPtGa

def PlotAndSaveRGBAndRGBNoPtGa(RGBElements, equalizeRGB=True, cutnoiseRGB=True, equalizeNoPtGa=True, cutnoiseNoPtGa=True):
    Img1 = MakeRGBFromMaps(ElementDict[RGBElements[0]],ElementDict[RGBElements[1]],ElementDict[RGBElements[2]], 
                      equalize=equalizeRGB, cutnoise=cutnoiseRGB)
    #Img1.plot()
    Img1.save(os.path.join(f'{BinningFactor}bin', 'Maps', RGBElements[0]+RGBElements[1]+RGBElements[2]+'.tif'), overwrite=True)
    Img2 = MakeRGBFromMaps(ElementDictNoPtGa[RGBElements[0]],ElementDictNoPtGa[RGBElements[1]],ElementDictNoPtGa[RGBElements[2]], 
                          equalize=equalizeNoPtGa, cutnoise=cutnoiseNoPtGa)
    #Img2.plot()
    Img2.save(os.path.join(f'{BinningFactor}bin', 'MapsNoPtGa', RGBElements[0]+RGBElements[1]+RGBElements[2]+'.tif'), overwrite=True)
    hs.plot.plot_images([Img1,Img2], colorbar=None)
    #plt.tight_layout()
/var/folders/85/3cpy93dj3lj305c8bq9_1zn40000gn/T/ipykernel_19383/91351839.py:6: DeprecationWarning: Importing display from IPython.core.display is deprecated since IPython 7.14, please import from IPython display
  from IPython.core.display import display, HTML
In [2]:
HAADF, EDS = hs.load(StackName)
print(f'Stack dimensions are: {EDS.data.shape}.')
if BinningFactor > 1:
    EDS = EDS.rebin(scale=(BinningFactor, BinningFactor, 1))
    print(f'New stack dimensions are: {EDS.data.shape} with binning: {BinningFactor}')
EDS.plot()

HAADF.save(os.path.join(f'{BinningFactor}bin', 'Maps', 'HAADF.tif'), overwrite=True)
HAADF.save(os.path.join(f'{BinningFactor}bin', 'MapsNoPtGa', 'HAADF.tif'), overwrite=True)
Stack dimensions are: (188, 488, 2048).
In [3]:
print(HAADF.metadata)
print(EDS.metadata)
├── Acquisition_instrument
│   └── TEM
│       ├── beam_energy = 80
│       └── magnification = 14000
├── General
│   ├── FileIO
│   │   ├── 0
│   │   │   ├── hyperspy_version = 1.7.3
│   │   │   ├── io_plugin = hyperspy.io_plugins.bruker
│   │   │   ├── operation = load
│   │   │   └── timestamp = 2023-02-14T15:09:30.604271-08:00
│   │   ├── 1
│   │   │   ├── hyperspy_version = 1.7.3
│   │   │   ├── io_plugin = hyperspy.io_plugins.tiff
│   │   │   ├── operation = save
│   │   │   └── timestamp = 2023-02-14T15:09:31.314683-08:00
│   │   └── 2
│   │       ├── hyperspy_version = 1.7.3
│   │       ├── io_plugin = hyperspy.io_plugins.tiff
│   │       ├── operation = save
│   │       └── timestamp = 2023-02-14T15:09:31.319014-08:00
│   ├── original_filename = Stack.bcf
│   └── title = HAADF
├── Sample
│   └── name = 1
└── Signal
    └── signal_type = 

├── Acquisition_instrument
│   └── TEM
│       ├── Detector
│       │   └── EDS
│       │       ├── azimuth_angle = 45.0
│       │       ├── detector_type = Custom type
│       │       ├── elevation_angle = 18.0
│       │       ├── energy_resolution_MnKa = 130.0
│       │       ├── live_time = 2898.543
│       │       └── real_time = 3060.3455999999996
│       ├── Stage
│       │   └── tilt_alpha = 0.0
│       ├── beam_energy = 80
│       └── magnification = 14000
├── General
│   ├── FileIO
│   │   └── 0
│   │       ├── hyperspy_version = 1.7.3
│   │       ├── io_plugin = hyperspy.io_plugins.bruker
│   │       ├── operation = load
│   │       └── timestamp = 2023-02-14T15:09:30.611420-08:00
│   ├── date = 2022-03-18
│   ├── original_filename = Stack.bcf
│   ├── time = 21:57:12
│   └── title = EDX
├── Sample
│   ├── elements = ['Al', 'C', 'Ca', 'Cu', 'Fe', 'Ga', 'Mg', 'Na', 'Ni', 'O', 'Pt', 'S', 'Si', 'Ti']
│   ├── name = 1
│   └── xray_lines = ['Al_Ka', 'C_Ka', 'Ca_Ka', 'Cu_Ka', 'Fe_Ka', 'Ga_Ka', 'Mg_Ka', 'Na_Ka', 'Ni_Ka', 'O_Ka', 'Pt_La', 'S_Ka', 'Si_Ka', 'Ti_Ka']
└── Signal
    ├── quantity = X-rays (Counts)
    └── signal_type = EDS_TEM

In [7]:
sumspec = EDS.sum()
sumspec.add_lines()
ElLines = ['C_Ka', 'N_Ka', 'O_Ka', 'Na_Ka', 'Pt_La', 'Mg_Ka', 'Al_Ka', 'Si_Ka', 'P_Ka', 'S_Ka', 'Cl_Ka', 'Cs_La', 'K_Ka', 'Ca_Ka', 'Ti_Ka', 'Cr_Ka', 'Mn_Ka', 'Fe_Ka', 'Ni_Ka', 'Zn_Ka', 'Cu_Ka', 'Ga_Ka', 'Cs_Ka' ]
Elements = EDS.get_lines_intensity(ElLines)
Elements = [El.T for El in Elements]
ElementDict = dict()
for El in Elements:
    El.change_dtype('uint16')
    El.save(os.path.join(f'{BinningFactor}bin', 'Maps', El.metadata.Sample.xray_lines[0]+'.tif'), overwrite=True)
    ElementDict[El.metadata.Sample.elements[0]] = El
    #print(f'{El.metadata.Sample.elements[0]}')
    
ElementDictNoPtGa = RemovePtGaContamination(ElementDict)
ElementsNoPtGa = [El for El in ElementDictNoPtGa.values()]
for El in Elements:
    El.save(os.path.join(f'{BinningFactor}bin', 'MapsNoPtGa', El.metadata.Sample.xray_lines[0]+'.tif'), overwrite=True)
sumspec.plot(True, norm='log')
sumspec.save(os.path.join(f'{BinningFactor}bin' f'SumSpectrum.msa'), overwrite=True)
plt.savefig(os.path.join(f'{BinningFactor}bin' f'SumSpectrum.png'), dpi=300)
In [8]:
fig = plt.figure(figsize=(20,20))
hs.plot.plot_images(Elements, per_row=int(ceil(sqrt(len(Elements)))), colorbar=None, axes_decor='off', fig=fig)
plt.show()
fig.savefig(os.path.join(f'{BinningFactor}bin', 'Maps', 'Mosaic.png'))
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [8], in <cell line: 2>()
      1 fig = plt.figure(figsize=(20,20))
----> 2 hs.plot.plot_images(Elements, per_row=int(ceil(sqrt(len(Elements)))), colorbar=None, axes_decor='off', fig=fig)
      3 plt.show()
      4 fig.savefig(os.path.join(f'{BinningFactor}bin', 'Maps', 'Mosaic.png'))

NameError: name 'ceil' is not defined
In [9]:
fig = plt.figure(figsize=(20,20))
hs.plot.plot_images(ElementsNoPtGa, per_row=int(ceil(sqrt(len(ElementsNoPtGa)))), colorbar=None, axes_decor='off', fig=fig)
plt.show()
fig.savefig(os.path.join(f'{BinningFactor}bin', 'MapsNoPtGa', 'Mosaic.png'))
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [9], in <cell line: 2>()
      1 fig = plt.figure(figsize=(20,20))
----> 2 hs.plot.plot_images(ElementsNoPtGa, per_row=int(ceil(sqrt(len(ElementsNoPtGa)))), colorbar=None, axes_decor='off', fig=fig)
      3 plt.show()
      4 fig.savefig(os.path.join(f'{BinningFactor}bin', 'MapsNoPtGa', 'Mosaic.png'))

NameError: name 'ceil' is not defined
In [10]:
PlotAndSaveRGBAndRGBNoPtGa(['Fe', 'Mg', 'O'], equalizeRGB=True, cutnoiseRGB=True)
[########################################] | 100% Completed | 102.78 ms
/Users/Zack/opt/anaconda3/envs/conda310/lib/python3.10/site-packages/hyperspy/signal.py:2451: UserWarning: Setting the `metadata` attribute is deprecated and will be removed in HyperSpy 2.0. Use the `set_item` and `add_dictionary` methods of the `metadata` attribute instead.
  warnings.warn(
/Users/Zack/opt/anaconda3/envs/conda310/lib/python3.10/site-packages/hyperspy/signal.py:2467: UserWarning: Setting the `original_metadata` attribute is deprecated and will be removed removed in HyperSpy 2.0. Use the `set_item` and `add_dictionary` methods of the `original_metadata` attribute instead.
  warnings.warn(
[########################################] | 100% Completed | 107.58 ms
In [11]:
PlotAndSaveRGBAndRGBNoPtGa(['Fe', 'Si', 'S'])
[########################################] | 100% Completed | 105.65 ms
[########################################] | 100% Completed | 101.87 ms
In [12]:
PlotAndSaveRGBAndRGBNoPtGa(['Al', 'O', 'Si'])
[########################################] | 100% Completed | 106.76 ms
[########################################] | 100% Completed | 102.06 ms
In [13]:
PlotAndSaveRGBAndRGBNoPtGa(['Fe', 'Ni', 'S'])
[########################################] | 100% Completed | 105.34 ms
[########################################] | 100% Completed | 105.81 ms
In [14]:
PlotAndSaveRGBAndRGBNoPtGa(['C', 'N', 'O'])
[########################################] | 100% Completed | 105.22 ms
[########################################] | 100% Completed | 101.75 ms
In [15]:
PlotAndSaveRGBAndRGBNoPtGa(['Al', 'Mg', 'O'], equalizeNoPtGa=False, cutnoiseNoPtGa=True)
[########################################] | 100% Completed | 103.41 ms
[########################################] | 100% Completed | 105.64 ms
In [16]:
PlotAndSaveRGBAndRGBNoPtGa(['Al', 'Ca', 'Cr'], equalizeNoPtGa=False, cutnoiseNoPtGa=False)
[########################################] | 100% Completed | 103.76 ms
[########################################] | 100% Completed | 103.75 ms
In [17]:
PlotAndSaveRGBAndRGBNoPtGa(['Na', 'K', 'Al'], equalizeNoPtGa=False, cutnoiseNoPtGa=False)
[########################################] | 100% Completed | 102.65 ms
[########################################] | 100% Completed | 102.65 ms
In [18]:
PlotAndSaveRGBAndRGBNoPtGa(['C', 'S', 'Cs'], equalizeRGB=True, cutnoiseRGB=False)
[########################################] | 100% Completed | 104.71 ms
[########################################] | 100% Completed | 103.33 ms
In [19]:
%%javascript
IPython.notebook.save_notebook()
In [22]:
!jupyter-nbconvert --to html "Plot Bruker Stack.ipynb"
!cp "Plot Bruker Stack.html" {BinningFactor}bin
[NbConvertApp] Converting notebook Plot Bruker Stack.ipynb to html
Traceback (most recent call last):
  File "/Users/Zack/opt/anaconda3/envs/conda310/bin/jupyter-nbconvert", line 11, in <module>
    sys.exit(main())
  File "/Users/Zack/opt/anaconda3/envs/conda310/lib/python3.10/site-packages/jupyter_core/application.py", line 269, in launch_instance
    return super().launch_instance(argv=argv, **kwargs)
  File "/Users/Zack/opt/anaconda3/envs/conda310/lib/python3.10/site-packages/traitlets/config/application.py", line 846, in launch_instance
    app.start()
  File "/Users/Zack/opt/anaconda3/envs/conda310/lib/python3.10/site-packages/nbconvert/nbconvertapp.py", line 369, in start
    self.convert_notebooks()
  File "/Users/Zack/opt/anaconda3/envs/conda310/lib/python3.10/site-packages/nbconvert/nbconvertapp.py", line 541, in convert_notebooks
    self.convert_single_notebook(notebook_filename)
  File "/Users/Zack/opt/anaconda3/envs/conda310/lib/python3.10/site-packages/nbconvert/nbconvertapp.py", line 506, in convert_single_notebook
    output, resources = self.export_single_notebook(notebook_filename, resources, input_buffer=input_buffer)
  File "/Users/Zack/opt/anaconda3/envs/conda310/lib/python3.10/site-packages/nbconvert/nbconvertapp.py", line 435, in export_single_notebook
    output, resources = self.exporter.from_filename(notebook_filename, resources=resources)
  File "/Users/Zack/opt/anaconda3/envs/conda310/lib/python3.10/site-packages/nbconvert/exporters/exporter.py", line 190, in from_filename
    return self.from_file(f, resources=resources, **kw)
  File "/Users/Zack/opt/anaconda3/envs/conda310/lib/python3.10/site-packages/nbconvert/exporters/exporter.py", line 208, in from_file
    return self.from_notebook_node(nbformat.read(file_stream, as_version=4), resources=resources, **kw)
  File "/Users/Zack/opt/anaconda3/envs/conda310/lib/python3.10/site-packages/nbconvert/exporters/html.py", line 210, in from_notebook_node
    return super().from_notebook_node(nb, resources, **kw)
  File "/Users/Zack/opt/anaconda3/envs/conda310/lib/python3.10/site-packages/nbconvert/exporters/templateexporter.py", line 392, in from_notebook_node
    output = self.template.render(nb=nb_copy, resources=resources)
  File "/Users/Zack/opt/anaconda3/envs/conda310/lib/python3.10/site-packages/jinja2/environment.py", line 1301, in render
    self.environment.handle_exception()
  File "/Users/Zack/opt/anaconda3/envs/conda310/lib/python3.10/site-packages/jinja2/environment.py", line 936, in handle_exception
    raise rewrite_traceback_stack(source=source)
  File "/Users/Zack/opt/anaconda3/envs/conda310/share/jupyter/nbconvert/templates/lab/index.html.j2", line 3, in top-level template code
    {% from 'jupyter_widgets.html.j2' import jupyter_widgets %}
  File "/Users/Zack/opt/anaconda3/envs/conda310/share/jupyter/nbconvert/templates/lab/base.html.j2", line 260, in top-level template code
    {% set div_id = uuid4() %}
  File "/Users/Zack/opt/anaconda3/envs/conda310/share/jupyter/nbconvert/templates/base/display_priority.j2", line 1, in top-level template code
    {%- extends 'base/null.j2' -%}
  File "/Users/Zack/opt/anaconda3/envs/conda310/share/jupyter/nbconvert/templates/base/null.j2", line 24, in top-level template code
    {%- block header -%}
  File "/Users/Zack/opt/anaconda3/envs/conda310/share/jupyter/nbconvert/templates/lab/index.html.j2", line 9, in block 'header'
    {%- block html_head -%}
  File "/Users/Zack/opt/anaconda3/envs/conda310/share/jupyter/nbconvert/templates/lab/index.html.j2", line 36, in block 'html_head'
    {% block notebook_css %}
  File "/Users/Zack/opt/anaconda3/envs/conda310/share/jupyter/nbconvert/templates/lab/index.html.j2", line 37, in block 'notebook_css'
    {{ resources.include_css("static/index.css") }}
  File "/Users/Zack/opt/anaconda3/envs/conda310/lib/python3.10/site-packages/nbconvert/exporters/html.py", line 216, in resources_include_css
    return jinja2.Markup(code)
AttributeError: module 'jinja2' has no attribute 'Markup'
cp: Plot Bruker Stack.html: No such file or directory
In [21]:
%%javascript
IPython.notebook.save_notebook()
In [ ]:
 
In [ ]: