<jupyter_start><jupyter_text>Using DataYoink's Pretrained Mask This demo is inteded for users who have images of battery discharge curves from which they want to extract points. This can be accomplished easily by following the steps below in a jupyter notebook.  Step 1: Import all requred packages The import statements below may need to be modified based on where the requred .py files appear in your directory<jupyter_code>from pyfiles_for_demos.coordconverter import datayoink_to_excel, get_axis_info
from pyfiles_for_demos.img_rescale import img_rescale
from pyfiles_for_demos.predict import predict_discharge_curve
from pyfiles_for_demos.predict import show_output_img_and_mask
from pyfiles_for_demos.pointclassifier import pointclassifier

import matplotlib
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
matplotlib.rcParams.update({'font.size': 26})
%matplotlib inline
%matplotlib notebook

import ipywidgets as wdg
from ipywidgets import ToggleButtons

import pandas as pd
import numpy as np
import math

import xlsxwriter<jupyter_output>** fvcore version of PathManager will be deprecated soon. **
** Please migrate to the version in iopath repo. **
https://github.com/facebookresearch/iopath 

** fvcore version of PathManager will be deprecated soon. **
** Please migrate to the version in iopath repo. **
https://github.com/facebookresearch/iopath<jupyter_text>Step 2:  Load and resize ImageStore the path to the figure you want to make prediction on in the variable *image_PNG*. REsize the image to the desired image height and width by specifying the variables *image_height* and *image_width*. This can be used to downsize an image for faster prediction. The pretrained mm is trained by 400(height) by 600(width) images. Resizing your image to this scale might improve the prediction accuracy.<jupyter_code>image_PNG = "Test_bw.png"
image_height = 400
image_width = 600
rescaled_img = img_rescale(image_PNG, image_height, image_width)<jupyter_output>original image shape: (1493, 2583) is scaled to new image shape (400, 600)<jupyter_text>Step 3: Provide information about the image  Once you run the cell below, in the plot area, use your mouse to click on the following: * 1.) Origin * 2.) X-axis max (this should match the location of the ```x max value``` entered below)* 3.) Y-axis max (this should match the location of the ```y max value``` entered below)  Notes:* These points are used to establish scaling between pixels and coordinate locations on the graph area and will affect the accuracy of the values saved in the final excel file* Be careful not to accidentally add extra clicks, in the case you do, re-run the cell* Below the plot, there is a textbox named "event:" where, everytime you click on the image, a event is captured at the position where you clicked your mouse on the image, verify there is only 3 points selected (scroll down before you start clicking)* Use the horizontal scroll bar below the image if part of your plot is cut-off<jupyter_code># Initialize array of x and y pixels
x = []
y = []


# Load in a discharge curve
img = mpimg.imread("Test_bw.png")
fig = plt.figure(figsize=(15,10))
plt.imshow(img)
plt.axis('off')

# Create and display textarea widget
txt = wdg.Textarea(
    value='',
    placeholder='',
    description='event:',
    disabled=False)
display(txt)
print("please select")

# Function to record mouse click events
def onclick(event):
    txt.value = str(event)  # Dynamically update the text box above
    # Create an hard reference to the callback not to be cleared by the garbage collector
    x.append(event.xdata)
    y.append(event.ydata)
ka = fig.canvas.mpl_connect('button_press_event', onclick)<jupyter_output><empty_output><jupyter_text>Results of selected points:<jupyter_code>xpixels = [round(num, -1) for num in x]
ypixels = [round(num, -1) for num in y]
print("the x coordinates are", xpixels)
print("the y coordinates are", ypixels)
userpoints = np.column_stack( (xpixels, ypixels) )
origin, xpixelmax, ypixelmax = pointclassifier(userpoints)<jupyter_output>[ 210. 1270.] is the pixel location of the origin
[2490. 1280.] is the pixel location of the x-axis max
[210.  50.] is the pixel location of the y-axis max<jupyter_text>Next, define the range of the x and y axes by answering prompts:The image is recreated below for reference. Answer in the units provided in the graph.<jupyter_code>fig = plt.figure(figsize=(10, 5))
plt.imshow(img)
plt.axis('off')
xcoordinatemin = float(input("Enter the x min value on the x-axis:"))
xcoordinatemax = float(input("Enter the x max value on the x-axis:"))
ycoordinatemin = float(input("Enter the y min value on the y-axis:"))
ycoordinatemax = float(input("Enter the y max value on the y-axis:"))


assert type(xcoordinatemin) == float, 'User input for the min X value on the x-axis is not the correct datatype'
assert type(xcoordinatemin) == float, 'User input for the max X value on the y-axis is not the correct datatype'
assert xcoordinatemin < xcoordinatemax, 'The min X value on the x-axis is greater than the max X value on the x-axis'
assert type(ycoordinatemin) == float, 'User input for the min Y value on the y-axis is not the correct datatype'
assert type(ycoordinatemin) == float, 'User input for the max Y value on the y-axis is not the correct datatype'
assert ycoordinatemin < ycoordinatemax, 'The min Y value on the y-axis is greater than the max Y value on the y-axis'
print("the range of the x-axis is", "(", xcoordinatemin, ",", xcoordinatemax, ")")
print("the range of the y-axis is", "(", ycoordinatemin, ",", ycoordinatemax, ")")<jupyter_output>the range of the x-axis is ( 0.0 , 1.2 )
the range of the y-axis is ( 0.0 , 1.6 )<jupyter_text>Specify the maximum number of points you would like to see along the x axis:<jupyter_code>max_points = int(input("Enter the max number of points desired for the x-axis:"))


assert type(max_points) == int, 'User input for the number of points should be an integer'
assert max_points > 5, 'Choose more points'<jupyter_output>Enter the max number of points desired for the x-axis:5000<jupyter_text>Use the options below to select units along the x and y axes that match those in the graph<jupyter_code>xunits = ToggleButtons(options=['mAh/g', 'mAh', 'mAh/cm^2', 'μAh/g', 'μAh/cm^2', 'Ah/(g * V)'])
yunits = ToggleButtons(options=['Cycle Number', 'Voltage (V)'])
xunits
yunits
units = [xunits.value,yunits.value]
print("You have selected your x-axis units as:", xunits.value, "\nYou have selected your y-axis units as:", yunits.value)<jupyter_output>You have selected your x-axis units as: mAh 
You have selected your y-axis units as: Voltage (V)<jupyter_text>Step 4: Run detectron2 using the pretrained modelDownload the [pretrained nn] and the [configuration file] and place them in a folder named "output" in the current directory.- No Arguments need to be modified n the cell below- A new folder named "scaled_input_image" will be created in the current directory to stored the rescaeld .png input image<jupyter_code>pretrained_pkl = "./output/BEST_config.pkl"
outputs = predict_discharge_curve(pretrained_pkl,rescaled_img)
show_output_img_and_mask("scaled_input_image/scaled_"+image_PNG, outputs)<jupyter_output>/home/daniu/miniconda3/lib/python3.8/site-packages/detectron2/modeling/roi_heads/fast_rcnn.py:124: UserWarning: This overload of nonzero is deprecated:
	nonzero()
Consider using one of the following signatures instead:
	nonzero(*, bool as_tuple) (Triggered internally at  /pytorch/torch/csrc/utils/python_arg_parser.cpp:882.)
  filter_inds = filter_mask.nonzero()<jupyter_text>Step 5. Use DataYoink to save coordinates to excel The arguments for the following functions (except the filename, see below) do not need to be modified, they refer to variables already created by the above code.  Filenames:You may specify the base filename (in the datayoink_to_excel function) if desired. If only one image is run at a time, the resulting excel file will have the name ```filename```. If multiple are run at once (available in future versions), the files will have the names ```filename_1```, ```filename_2```, and so on.<jupyter_code>axis_info_dict = get_axis_info(xcoordinatemin, xcoordinatemax, xpixelmax,
                               ycoordinatemin, ycoordinatemax, ypixelmax,
                               origin, max_points, units)
datayoink_to_excel(outputs, axis_info_dict, filename='datayoink_result')<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.08311657602270041, 'fraction_numerical': 0.011113738472452117, 'mean_word_length': 5.143064633260711, 'pattern_counts': {'":': 0, '<': 32, '<?xml version=': 0, '>': 31, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '9', 'dir': 'jupyter-structured-clean-dedup', 'id': '36830', 'license': 'MIT', 'n_tokens_mistral': 2637, 'n_tokens_neox': 2534, 'n_words': 1052, 'path': 'examples/Demo_Using_Pretrained_Mask.ipynb', 'repo_name': 'DataYoink/DataYoink', 'size': '8458'}