<jupyter_start><jupyter_text>TFW Editor[Overview of Google Colaboratory Features](https://colab.research.google.com/notebooks/basic_features_overview.ipynb)[Primer for Learning Google Colaboratory](https://medium.com/dair-ai/primer-for-learning-google-colab-bb4cabca5dd6)[Colab Examples](https://colab.research.google.com/notebooks/welcome.ipynbrecent=true)  Libraries<jupyter_code>import sys
import numpy as np
import matplotlib.pyplot as plt
import scipy as sp
import scipy.signal

from bokeh.io import output_notebook, show, curdoc
from bokeh.plotting import figure
from bokeh.events import ButtonClick
from bokeh.models import ColumnDataSource, Button, CustomJS
from bokeh.models.widgets import DataTable, TableColumn, IntEditor, Button, TextInput
from bokeh.layouts import widgetbox
#from bokeh.layouts import widgetbox, gridplot

from google.colab import files, widgets

from ipywidgets import widgets as iwidgets

!git clone https://github.com/grkidwell/tfw_editor_bokeh.git
sys.path.append('tfw_editor_bokeh')
import tfwlib as tfw<jupyter_output>Cloning into 'tfw_editor_bokeh'...
remote: Enumerating objects: 74, done.[K
remote: Total 74 (delta 0), reused 0 (delta 0), pack-reused 74
Unpacking objects: 100% (74/74), done.<jupyter_text>Classes and Functions<jupyter_code>def on_change_data_source(attr, old, new):
    print('-- OLD DATA: {}'.format(old))
    print('-- NEW DATA: {}'.format(new))
    print('-- SOURCE DATA: {}'.format(source.data))

    # to check changes in the 'y' column:
    indices = list(range(len(old['y'])))
    changes = [(i,j,k) for i,j,k in zip(indices, old['y'], new['y']) if j != k]
    if changes != []:
        for t in changes:  # t = (index, old_val, new_val)
            patch = {
                'y' : [(t[0], int(t[2])), ]   # the new value is received as a string
            }
            source.patch(patch)   # this will call to this callback again, ugly
                                  # so you will need to update the values on another source variable
        print('-- SOURCE DATA AFTER PATCH: {}'.format(source.data))
        
class Three_state:
    
    def __init__(self,state1={'width':0.25e-6, 'level':1},
                      state2={'width':2.25e-6, 'level':0},
                      state3={'width':0,      'level':0}):
      
        self.state1,self.state2,self.state3 = state1,state2, state3
        self.t1,self.t2,self.t3=self.state1['width'],self.state2['width'],self.state3['width']
        self.lvl1,self.lvl2,self.lvl3=self.state1['level'],self.state2['level'],self.state3['level']
        
        self.Ts = self.t1+self.t2+self.t3
    
    def step(self,t):
        if t<0:
            kd=0.0
        elif t==0:
            kd=0.0
        else:
            kd=1.0
        return kd
            
    def t1_unit_pulse(self,t):
        if t<0:
            k=1.0
        else:
            k=self.step(self.t1-t)
        return k
      
    def t3_unit_pulse(self,t):
        return self.step(t-self.t1-self.t2)
      
    def t2_unit_pulse(self,t):
        return 1-self.t1_unit_pulse(t)-self.t3_unit_pulse(t)
    
    
    def t1_pulse(self,t):
        return self.lvl1*self.t1_unit_pulse(t)
    
    def t2_pulse(self,t):
        return self.lvl2*self.t2_unit_pulse(t)
    
    def t3_pulse(self,t):
        return self.lvl3*self.t3_unit_pulse(t)
      
    def pwm(self,t):
        return self.t1_pulse(t)+self.t2_pulse(t)+self.t3_pulse(t)
      
    def repeating(self,t):
        period=self.Ts
        return t-(t//period)*period<jupyter_output><empty_output><jupyter_text>Input Parameters<jupyter_code>Vin = 12
Vout = 1.2
fs = 0.5e6

duty = Vout/Vin
Ts = 1/fs
t1=duty*Ts
t2=(1-duty)*Ts

numdatapoints=2500  #Number determined by ARB waveform generator.  DO NOT CHANGE
numcycles = 25
tstep = np.round(numcycles*Ts/numdatapoints,9)<jupyter_output><empty_output><jupyter_text>Create single-pulse sequences<jupyter_code>#@title
highstatelvl=16382
tristatelvl=highstatelvl/2

tarray=np.arange(0,Ts,tstep, dtype=float)

normalcycleobject=Three_state(state1={'width':t1, 'level':highstatelvl},
                              state2={'width':t2, 'level':0.0})
normalcycle=np.vectorize(normalcycleobject.pwm)(tarray)


glitchcycleobject=Three_state(state1={'width':0.140e-6, 'level':tristatelvl},
                              state2={'width':0.120e-6, 'level':highstatelvl},
                              state3={'width':2.240e-6, 'level':0})
glitchcycle=np.vectorize(glitchcycleobject.pwm)(tarray)


f = plt.figure(figsize=(10,3))
ax = f.add_subplot(121)
ax2 = f.add_subplot(122)
ax.plot(normalcycle, 'b')
ax2.plot(glitchcycle, 'r')<jupyter_output><empty_output><jupyter_text>Create multi-cycle pulse sequence<jupyter_code>#start with glitch, then followed by multiple regular PWM cycles
data=np.int16(glitchcycle)
for i in range(numcycles-1):
  data=np.append(data,np.int16(normalcycle))
data.size
x=np.arange(data.size)
datapoints = dict(
        timeindex=x,
        amplitude=data,
    )
source = ColumnDataSource(datapoints)

#source.on_change('data', on_change_data_source)
columns = [
        TableColumn(field="timeindex", title="Time Index", editor=IntEditor()),
        TableColumn(field="amplitude", title="Waveform Amplitude", editor=IntEditor()),
    ]<jupyter_output><empty_output><jupyter_text>Plot Results<jupyter_code>#@title
data_table=DataTable(source=source,columns=columns,width=300, height=280, editable=True, selectable=True, sortable=True)
fig=figure(plot_height=400, plot_width=400)
fig.line(x='timeindex',y='amplitude', source=source,color='blue')
button = Button(label="Download datafile", button_type="success")
text_input = TextInput(placeholder="filename")#, title="Filename:")

def printfilename(attrname, old, new):
    print('duh')
    
#text_input.on_change('value', printfilename)

#show(widgetbox(text_input))
output_notebook()
grid=widgets.Grid(1,2)
with grid.output_to(0,0):
    show(data_table)
with grid.output_to(0,1):
    show(fig)<jupyter_output><empty_output><jupyter_text>Enter Filename to download<jupyter_code>#@title
file_name=input()
tfw.write_tfw(file_name, data)
files.download(file_name)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13680781758957655, 'fraction_numerical': 0.028175895765472313, 'mean_word_length': 3.767857142857143, 'pattern_counts': {'":': 0, '<': 30, '<?xml version=': 0, '>': 28, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '658367', 'license': 'MIT', 'n_tokens_mistral': 2307, 'n_tokens_neox': 2205, 'n_words': 390, 'path': 'tfwreadwrite_bokeh_pertubation_ncycle.ipynb', 'repo_name': 'grkidwell/tfw_editor_bokeh', 'size': '6140'}