markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
Convert unit of app size from GB into KB.
rating_df = app[["name","size","overall_rating", "current_rating", 'num_current_rating', "num_overall_rating"]].dropna() rating_cleaned = {'1 star':1, "1 and a half stars": 1.5, '2 stars': 2, '2 and a half stars':2.5, "3 stars":3, "3 and a half stars":3.5, "4 stars": 4, '4 and a half stars': 4.5, "5 st...
_____no_output_____
MIT
notebooks/Correlation between app size and app quality.ipynb
jpzhangvincent/MobileAppRecommendSys
Add variable weighted rating as app's quality into data set.
plt.scatter(rating_df['size'], rating_df['weighted_rating']) plt.xlabel('Size of app') plt.ylabel('Quality of app') plt.title('Relationship between app size and quality') plt.show() rating_df_2 = rating_df[rating_df['size'] <= 500] plt.scatter(rating_df_2['size'], rating_df_2['weighted_rating']) plt.xlabel('Size of app...
_____no_output_____
MIT
notebooks/Correlation between app size and app quality.ipynb
jpzhangvincent/MobileAppRecommendSys
environment(on conda) ```bashconda create -y -n holo python=3.7conda activate holo https://xarray.pydata.org/en/stable/getting-started-guide/installing.htmlinstructionsconda install -y -c conda-forge xarray dask netCDF4 bottleneckconda install -y -c conda-forge hvplotconda install -y -c conda-forge seleniumconda insta...
fs = glob.glob('out0*.nc') fs.sort() dd = [] for f in fs: ds = xr.open_dataset(f) U = ds['u'].values V = ds['v'].values Vmag = np.sqrt( U**2 + V**2) + 0.00000001 angle = (np.pi/2.) - np.arctan2(U/Vmag, V/Vmag) ds['Vmag'] = (['t','x','y'], Vmag) ds['angle'] =(['t','x','y'], angle) ds = ds...
_____no_output_____
MIT
makefig.ipynb
computational-sediment-hyd/2DH_Python
make html graph
fVec = dss.hvplot.vectorfield(x='x', y='y', groupby='t', angle='angle', mag='Vmag',hover=False) fVor = dss['vortex'].hvplot(frame_height=220, frame_width=600, x='x', y='y', cmap='bwr', clim=(-10,10)) g = fVor * fVec * fPoly g
_____no_output_____
MIT
makefig.ipynb
computational-sediment-hyd/2DH_Python
Thinning out for github
dssp = dss.isel( t=range(0,int(dss.dims['t']/2),10) ) fVec = dssp.hvplot.vectorfield(x='x', y='y', groupby='t', angle='angle', mag='Vmag',hover=False) fVor = dssp['vortex'].hvplot(frame_height=220, frame_width=600, x='x', y='y', cmap='bwr', clim=(-10,10)) g = fVor * fVec * fPoly
_____no_output_____
MIT
makefig.ipynb
computational-sediment-hyd/2DH_Python
export html
d = hvplot.save(g,'out.html') del d
_____no_output_____
MIT
makefig.ipynb
computational-sediment-hyd/2DH_Python
export png
%%time for i, t in enumerate( dssp['t'].values ): gp = g[t].options(title=str(np.round(t,3)) + ' sec', toolbar=None) d = hvplot.save(gp,'png'+str(i).zfill(8) +'.png') del d
_____no_output_____
MIT
makefig.ipynb
computational-sediment-hyd/2DH_Python
make gif
from PIL import Image fs = glob.glob("*.png") imgs = [Image.open(f) for f in fs] # imgs = imgs[0:501:2] # appendした画像配列をGIFにする。durationで持続時間、loopでループ数を指定可能。 d= imgs[0].save('out.gif', save_all=True, append_images=imgs[1:], optimize=False, duration=0.5, loop=0) del d
_____no_output_____
MIT
makefig.ipynb
computational-sediment-hyd/2DH_Python
1D convolution
b = np.random.random(4) a = np.random.random(10) np.convolve(a, b) def convolve(a, b): if a.shape[0] < b.shape[0]: a, b = b, a return np.array([ # important to remember the [::-1] np.matmul(a[i:i+b.shape[0]], b[::-1]) # \equiv dot().sum() for i in range(a.s...
_____no_output_____
MIT
misc/deep_learning_notes/Ch4_Recurrent_Networks/001_Optimization_Algorithms_and_Hyper-parameter_Search/Higher_Dimentional_Convolutions.ipynb
tmjnow/MoocX
2D convolution
a = np.random.random((3, 6)) b = np.random.random((2, 2)) # 2D convolution def convolve2d(a, b): #a_f = a.flatten().reshape((a.size, 1)) #b_f = b.flatten().reshape((1, b.size)) return np.array( [ [ (a[i:i+b.shape[0], j:j+b.shape[1]]* b[::-1,::-1]).sum() ...
[[ 0.00000000e+00 1.11022302e-16 0.00000000e+00 0.00000000e+00 0.00000000e+00] [ 0.00000000e+00 0.00000000e+00 0.00000000e+00 2.22044605e-16 2.22044605e-16]]
MIT
misc/deep_learning_notes/Ch4_Recurrent_Networks/001_Optimization_Algorithms_and_Hyper-parameter_Search/Higher_Dimentional_Convolutions.ipynb
tmjnow/MoocX
results in the difference are from floating point imprecision. 3D convolution (for video applications)
a = np.random.random((3, 6, 4)) b = np.random.random((2, 2, 3)) # 2D convolution def convolve3d(a, b): #a_f = a.flatten().reshape((a.size, 1)) #b_f = b.flatten().reshape((1, b.size)) return np.array( [ [ [ (a[i:i+b.shape[0], j:j+b.shape[1], k:k+b....
_____no_output_____
MIT
misc/deep_learning_notes/Ch4_Recurrent_Networks/001_Optimization_Algorithms_and_Hyper-parameter_Search/Higher_Dimentional_Convolutions.ipynb
tmjnow/MoocX
... ***CURRENTLY UNDER DEVELOPMENT*** ... Obtain synthetic waves and water level timeseries under a climate change scenario (future AWTs occurrence probability)inputs required: * Historical DWTs (for plotting) * Historical wave families (for plotting) * Synthetic DWTs climate change * Historical intradaily hydrog...
#!/usr/bin/env python # -*- coding: utf-8 -*- # common import os import os.path as op # pip import numpy as np import xarray as xr import pandas as pd from datetime import datetime import matplotlib.pyplot as plt # DEV: override installed teslakit import sys sys.path.insert(0, op.join(os.path.abspath(''), '..', '..'...
_____no_output_____
MIT
notebooks/ROI/03_ClimateChange/S5_SLR_ENSO/01_12_Climate_Emulator.ipynb
teslakit/teslak
Database and Site parameters
# -------------------------------------- # Teslakit database p_data = r'/Users/anacrueda/Documents/Proyectos/TESLA/data' # offshore db = Database(p_data) db.SetSite('ROI') # climate change - S5 db_S5 = Database(p_data) db_S5.SetSite('ROI_CC_S5') # climate emulator simulation modified path p_S5_CE_sims = op.join(db...
<xarray.Dataset> Dimensions: (n_sim: 10, time: 365244) Coordinates: * time (time) object 2000-01-01 00:00:00 ... 3000-01-01 00:00:00 Dimensions without coordinates: n_sim Data variables: evbmus_sims (time, n_sim) float32 ... Attributes: source: teslakit_v0.9.1
MIT
notebooks/ROI/03_ClimateChange/S5_SLR_ENSO/01_12_Climate_Emulator.ipynb
teslakit/teslak
Climate Emulator - Simulation
# -------------------------------------- # Climate Emulator extremes model fitting # Load Climate Emulator CE = Climate_Emulator(db.paths.site.EXTREMES.climate_emulator) CE.Load() # set a new path for S5 simulations CE.Set_Simulation_Folder(p_S5_CE_sims, copy_WAVES_noTCs = False) # climate change waves (no TCs) not ...
- Sim: 1 -
MIT
notebooks/ROI/03_ClimateChange/S5_SLR_ENSO/01_12_Climate_Emulator.ipynb
teslakit/teslak
Strings in Python What is a string? A "string" is a series of characters of arbitrary length.Strings are immutable - they cannot be changed once created. When you modify a string, you automatically make a copy and modify the copy.
s1 = 'Godzilla' print s1, s1.upper(), s1
_____no_output_____
MIT
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
String literals A "literal" is essentially a string constant, already spelled out for you. Python uses either on output, but that's just for formatting simplicity.
"Godzilla"
_____no_output_____
MIT
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
Single and double quotes Generally, a string literal can be in single ('), double ("), or triple (''') quotes. Single and double quotes are equivalent - use whichever you prefer (but be consistent). If you need to have a single or double quote in your literal, surround your literal with the other type, or use the back...
"Godzilla's a kaiju." 'Godzilla\'s a kaiju.' 'We call him... "Godzilla".'
_____no_output_____
MIT
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
Triple quotes (''') Triple quotes are a special form of quoting used for documenting your Python files (docstrings). We won't discuss that type here. Raw strings Raw strings don't use any escape character interpretation. Use them when you have a complicated string that you don't want to clutter with lots of backslash...
print('This is a\ncomplicated string with newline escapes in it.') print(r'This is a\ncomplicated string with newline escapes in it.')
_____no_output_____
MIT
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
Strings and numbers
x=int('122', 3) x+1
_____no_output_____
MIT
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
String objects String objects are just the string variables you create in Python.
kaiju = 'Godzilla' print(kaiju) kaiju
_____no_output_____
MIT
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
Note the print() call shows no quotes, while the simple variable name did. That is a Python output convention. Just entering the name will call the repr() method, which displays the value of the argument as Python would see it when it reads it in, not as the user wants it.
repr(kaiju) print(repr(kaiju))
_____no_output_____
MIT
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
String operators When you read text from a file, it's just that - text. No matter what the data represents, it's still text. To use it as a number, you have to explicitly convert it to a number.
one = 1 two = '2' print one, two, one + two one = 1 two = int('2') print one, two, one + two num1 = 1.1 num2 = float('2.2') print num1, num2, num1 + num2
_____no_output_____
MIT
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
You can also do this with hexadecimal and octal numbers, or any other base, for that matter.
print int('FF', 16) print int('0xff', 16) print int('777', 8) print int('0777', 8) print int('222', 7) print int('110111001', 2)
_____no_output_____
MIT
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
If the conversion cannot be done, an exception is thrown.
print int('0xGG', 16)
_____no_output_____
MIT
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
Concatenation
kaiju1 = 'Godzilla' kaiju2 = 'Mothra' kaiju1 + ' versus ' + kaiju2
_____no_output_____
MIT
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
Repetition
'Run away! ' * 3
_____no_output_____
MIT
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
String keywords in() NOTE: This _particular_ statement is false regardless of how the statement is evaluated! :^)
'Godzilla' in 'Godzilla vs Gamera'
_____no_output_____
MIT
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
String functions len()
len(kaiju)
_____no_output_____
MIT
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
String methods Remember - methods are functions attached to objects, accessed via the 'dot' notation. Basic formatting and manipulation capitalize()/lower()/upper()/swapcase()/title()
kaiju.capitalize() kaiju.lower() kaiju.upper() kaiju.swapcase() 'godzilla, king of the monsters'.title()
_____no_output_____
MIT
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
center()/ljust()/rjust()
kaiju.center(20, '*') kaiju.ljust(20, '*') kaiju.rjust(20, '*')
_____no_output_____
MIT
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
expandtabs()
tabbed_kaiju = '\tGodzilla' print('[' + tabbed_kaiju + ']') print('[' + tabbed_kaiju.expandtabs(16) + ']')
_____no_output_____
MIT
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
join()
' vs '.join(['Godzilla', 'Hedorah']) ','.join(['Godzilla', 'Mothra', 'King Ghidorah'])
_____no_output_____
MIT
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
strip()/lstrip()/rstrip()
' Godzilla '.strip() 'xxxGodzillayyy'.strip('xy') ' Godzilla '.lstrip() ' Godzilla '.rstrip()
_____no_output_____
MIT
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
partition()/rpartition()
battle = 'Godzilla x Gigan' battle.partition(' x ') battle = 'Godzilla and Jet Jaguar vs. Gigan and Megalon' battle.partition(' vs. ') battle = 'Godzilla vs Megalon vs Jet Jaguar' battle.partition('vs') battle = 'Godzilla vs Megalon vs Jet Jaguar' battle.rpartition('vs')
_____no_output_____
MIT
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
replace()
battle = 'Godzilla vs Mothra' battle.replace('Mothra', 'Anguiras') battle = 'Godzilla vs a monster and another monster' battle.replace('monster', 'kaiju', 2) battle = 'Godzilla vs a monster and another monster and yet another monster' battle.replace('monster', 'kaiju', 2)
_____no_output_____
MIT
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
split()/rsplit()
battle = 'Godzilla vs King Ghidorah vs Mothra' battle.split(' vs ') kaijus = 'Godzilla,Mothra,King Ghidorah' kaijus.split(',') kaijus = 'Godzilla Mothra King Ghidorah' kaijus.split() kaijus = 'Godzilla,Mothra,King Ghidorah,Megalon' kaijus.rsplit(',', 2)
_____no_output_____
MIT
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
splitlines()
kaijus_in_lines = 'Godzilla\nMothra\nKing Ghidorah\nEbirah' print(kaijus_in_lines) kaijus_in_lines.splitlines() kaijus_in_lines.splitlines(True)
_____no_output_____
MIT
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
zfill()
age_of_Godzilla = 60 age_string = str(age_of_Godzilla) print(age_string, age_string.zfill(5))
_____no_output_____
MIT
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
String information isXXX()
print('Godzilla'.isalnum()) print('*Godzilla*'.isalnum()) print('Godzilla123'.isalnum()) print('Godzilla'.isalpha()) print('Godzilla123'.isalpha()) print('Godzilla'.isdigit()) print('60'.isdigit()) print('SpaceGodzilla'.isspace()) print(' '.isspace()) print('Godzilla'.islower()) print('godzilla'.islower()) print('God...
_____no_output_____
MIT
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
count()
monsters = 'Godzilla and Space Godzilla and MechaGodzilla' print 'There are ', monsters.count('Godzilla'), ' Godzillas.' print 'There are ', monsters.count('Godzilla', len('Godzilla')), ' pseudo-Godzillas.'
_____no_output_____
MIT
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
startswith()/endswith()
king_kaiju = 'Godzilla' print king_kaiju.startswith('God') print king_kaiju.endswith('lla') print king_kaiju.startswith('G') print king_kaiju.endswith('amera')
_____no_output_____
MIT
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
find()/index()/rfind()/rindex()
kaiju_string = 'Godzilla,Gamera,Gorgo,Space Godzilla' print 'The first Godz is at position', kaiju_string.find('Godz') print 'The second Godz is at position', kaiju_string.find('Godz', len('Godz')) kaiju_string.index('Minilla') kaiju_string.rindex('Godzilla')
_____no_output_____
MIT
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
Advanced features decode()/encode()/translate() Used to convert strings to/from Unicode and other systems. Rarely used in science code. String formatting Similar to formatting in C, FORTRAN, etc.. There is a _lot_ more to this than I am showing here.
kaiju = 'Godzilla' age = 60 print '%s is %d years old.' % (kaiju, age)
_____no_output_____
MIT
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
The _string_ module The _string_ module is the Python equivalent of "junk DNA" in living organisms. It's been around since the beginning, but many of its functions have been superseded by evolution. But some ancient code still relies on it, so they leave the old parts in....For modern code, the _string_ module does ha...
import string print string.ascii_letters print string.ascii_lowercase print string.ascii_uppercase print string.digits print string.hexdigits print string.octdigits print string.letters print string.lowercase print string.uppercase print string.printable print string.punctuation print string.whitespace
_____no_output_____
MIT
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
The _string_ module also provides the _Formatter_ class, which can be useful for sophisticated text formatting. Regular Expressions What is a regular expression? Regular expressions ('regexps') are essentially a mini-language for describing string operations. Everything shown above with string methods and operators c...
import re
_____no_output_____
MIT
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
A very short, whirlwind tour of regular expressions Scanning
kaiju_truth = 'Godzilla is the King of the Monsters. Ebirah is also a monster, but looks like a giant lobster.' re.findall('Godz', kaiju_truth) print re.findall('(^.+) is the King', kaiju_truth)
_____no_output_____
MIT
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
For simple searches like this, using in() is typically easier.Regexps are by default case-sensitive.
print re.findall('\. (.+) is also', kaiju_truth) print re.findall('(.+) is also a (.+)', kaiju_truth)[0] print re.findall('\. (.+) is also a (.+),', kaiju_truth)[0]
_____no_output_____
MIT
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
Changing
some_kaiju = 'Godzilla, Space Godzilla, Mechagodzilla' print re.sub('Godzilla', 'Gamera', some_kaiju) print re.sub('(?i)Godzilla', 'Gamera', some_kaiju)
_____no_output_____
MIT
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
Intel® Distribution for GDB* In this notebook, we will cover using the Intel® Distribution for GDB* to debug oneAPI applications on the GPU. Sections- [Intel Distribution for GDB Overview](Intel-Distribution-for-GDB-Overview)- [How does the Intel Distribution for GDB debug GPUs?](How-does-Intel-Distribution-for-GDB-de...
! dpcpp -O0 -g src/array-transform.cpp -o bin/array-transform
_____no_output_____
MIT
DirectProgramming/DPC++/Jupyter/oneapi-essentials-training/11_Intel_Distribution_for_GDB/gdb_oneapi.ipynb
krisrak/oneAPI-samples
Create a debug scriptTo debug on the GPU, we're going to write the GDB debug commands to a file and then submit the execution of the debugger to a node with GPUs.In our first script, we'll get take a look at how inferiors, threads, and SIMD lanes are represented. Our debug script will perform the following tasks. 1. S...
%%writefile lab/array-transform.gdb #Set Breakpoint in the Kernel echo ================= (1) tbreak 59 ===============\n tbreak 59 # Run the application on the GPU echo ================= (2) run gpu ===============\n run gpu echo ================= (3) info inferiors ============\n info inferiors echo ==============...
_____no_output_____
MIT
DirectProgramming/DPC++/Jupyter/oneapi-essentials-training/11_Intel_Distribution_for_GDB/gdb_oneapi.ipynb
krisrak/oneAPI-samples
Start the DebuggerThe [run_debug.sh](run_debug.sh) script runs the *gdb-oneapi* executable with our debug script on the compiled application.Execute the following cell to submit the debug job to a node with a GPU.
! chmod 755 q; chmod 755 run_debug.sh; if [ -x "$(command -v qsub)" ]; then ./q run_debug.sh; else ./run_debug.sh; fi
_____no_output_____
MIT
DirectProgramming/DPC++/Jupyter/oneapi-essentials-training/11_Intel_Distribution_for_GDB/gdb_oneapi.ipynb
krisrak/oneAPI-samples
Explanation of Output1. You should see breakpoint 1 created at line 59.2. Application is run with the *gpu* argument to execute on the GPU device. Program should stop at the kernel breakpoint.3. With context now automatically switched to the device. The *info inferiors* command will show the active GDB inferior(s). He...
%%writefile lab/array-transform.gdb #Set Breakpoint in the Kernel echo ================= (1) break 59 ===============\n break 59 echo ================= (2) break 61 ===============\n break 61 # Run the application on the GPU echo ================= (3) run gpu ===============\n run gpu # Keep other threads stopped whi...
_____no_output_____
MIT
DirectProgramming/DPC++/Jupyter/oneapi-essentials-training/11_Intel_Distribution_for_GDB/gdb_oneapi.ipynb
krisrak/oneAPI-samples
Start Debugger Again To Examine Variables, MemoriesRun the following cell to run the debugger for the second time.
! chmod 755 q; chmod 755 run_debug.sh; if [ -x "$(command -v qsub)" ]; then ./q run_debug.sh; else ./run_debug.sh; fi
_____no_output_____
MIT
DirectProgramming/DPC++/Jupyter/oneapi-essentials-training/11_Intel_Distribution_for_GDB/gdb_oneapi.ipynb
krisrak/oneAPI-samples
Cyclical Systems: An Example of the Crank-Nicolson Method CH EN 2450 - Numerical Methods**Prof. Tony Saad (www.tsaad.net) Department of Chemical Engineering University of Utah**
import numpy as np from numpy import * # %matplotlib notebook # %matplotlib nbagg %matplotlib inline %config InlineBackend.figure_format = 'svg' # %matplotlib qt import matplotlib.pyplot as plt from scipy.optimize import fsolve from scipy.integrate import odeint def forward_euler(rhs, f0, tend, dt): ''' Computes t...
_____no_output_____
MIT
topics/initial-value-problems/Cyclical Example.ipynb
jomorodi/NumericalMethods
Sharp TransientSolve the ODE:\begin{equation}\frac{\text{d}y}{\text{d}t} = -1000 y + 3000 - 2000 e^{-t};\quad y(0) = 0\end{equation}The analytical solution is \begin{equation}y(t) = 3 - 0.998 e^{-1000t} - 2.002 e^{-t}\end{equation} We first plot the analytical solution
y = lambda t : 3 - 0.998*exp(-1000*t) - 2.002*exp(-t) t = np.linspace(0,1,500) plt.plot(t,y(t)) plt.grid()
_____no_output_____
MIT
topics/initial-value-problems/Cyclical Example.ipynb
jomorodi/NumericalMethods
Now let's solve this numerically. We first define the RHS for this function
def rhs_sharp_transient(f,t): return 3000 - 1000 * f - 2000* np.exp(-t)
_____no_output_____
MIT
topics/initial-value-problems/Cyclical Example.ipynb
jomorodi/NumericalMethods
Let's solve this using forward euler and backward euler
y0 = 0 tend = 0.03 dt = 0.001 t,yfe = forward_euler(rhs_sharp_transient,y0,tend,dt) t,ybe = backward_euler(rhs_sharp_transient,y0,tend,dt) t,ycn = crank_nicolson(rhs_sharp_transient,y0,tend,dt) plt.plot(t,y(t),label='Exact') # plt.plot(t,yfe,'r.-',markevery=1,markersize=10,label='Forward Euler') plt.plot(t,ybe,'k*-',m...
_____no_output_____
MIT
topics/initial-value-problems/Cyclical Example.ipynb
jomorodi/NumericalMethods
Oscillatory SystemsSolve the ODE:Solve the ODE:\begin{equation}\frac{\text{d}y}{\text{d}t} = r \omega \sin(\omega t)\end{equation}The analytical solution is \begin{equation}y(t) = r - r \cos(\omega t)\end{equation} First plot the analytical solution
r = 0.5 ω = 0.02 y = lambda t : r - r * cos(ω*t) t = np.linspace(0,100*pi) plt.clf() plt.plot(t,y(t)) plt.grid()
_____no_output_____
MIT
topics/initial-value-problems/Cyclical Example.ipynb
jomorodi/NumericalMethods
Let's solve this numerically
def rhs_oscillatory(f,t): r = 0.5 ω = 0.02 return r * ω * sin(ω*t) y0 = 0 tend = 100*pi dt = 10 t,yfe = forward_euler(rhs_oscillatory,y0,tend,dt) t,ybe = backward_euler(rhs_oscillatory,y0,tend,dt) t,ycn = crank_nicolson(rhs_oscillatory,y0,tend,dt) plt.plot(t,y(t),label='Exact') plt.plot(t,yfe,'r.-',markever...
_____no_output_____
MIT
topics/initial-value-problems/Cyclical Example.ipynb
jomorodi/NumericalMethods
Unsupervised neural computation - PracticalDependencies:- Python (>= 2.6 or >= 3.3)- NumPy (>= 1.6.1)- SciPy (>= 0.12)- SciKit Learn (>=0.18.1)Just as there are different ways in which we ourselves learn from our own surrounding environments, so it is with neural networks. In a broad sense, we may categorize the learn...
# Class implementing the basic RBF parametrization # based on code from https://github.com/jeffheaton/aifh import numpy as np class RbfFunction(object): def __init__(self, dimensions, params, index): self.dimensions = dimensions self.params = params self.index = index @property def...
_____no_output_____
MIT
code/UnsupervisedNeuralComputation.ipynb
caxenie/basecamp-winterschool-2017
RBFs can take various shapes: quadratic, multi-quadratic, inverse multi-quadratic, mexican hat. Yet the most used is the Gaussian.
# Class implementing a Gaussian RBF class RbfGaussian(RbfFunction): def evaluate(self, x): value = 0 width = self.width for i in range(self.dimensions): center = self.get_center(i) value += ((x[i] - center) ** 2) / (2.0 * width * width) return np.exp(-value)
_____no_output_____
MIT
code/UnsupervisedNeuralComputation.ipynb
caxenie/basecamp-winterschool-2017
A RBF network is an advanced machine learning algorithm that uses a series of RBF functions to perform regression. It can also perform classification by means of one-of-n encoding. The long term memory of a RBF network is made up of the widths and centers of the RBF functions, as well as input and output weighting.
# Class implementing a Gaussian RBF Network class RbfNetwork(object): def __init__(self, input_count, rbf_count, output_count): """ Create an RBF network with the specified shape. @param input_count: The input count. @param rbf_count: The RBF function count. @param output_count: Th...
_____no_output_____
MIT
code/UnsupervisedNeuralComputation.ipynb
caxenie/basecamp-winterschool-2017
The Iris dataset is a traditional benchmark in classification problems in ML. The data set consists of 50 samples from each of three species of Iris (Iris setosa, Iris virginica and Iris versicolor). Four features were measured from each sample: the length and the width of the sepals and petals, in centimetres. Based o...
# Find the dataset import os import sys from normalize import Normalize from error import ErrorCalculation from train import TrainAnneal import numpy as np irisFile = os.path.abspath("./data/iris.csv") # Read the Iris data set print('Reading CSV file: ' + irisFile) norm = Normalize() iris_work = norm.load_csv(irisFil...
_____no_output_____
MIT
code/UnsupervisedNeuralComputation.ipynb
caxenie/basecamp-winterschool-2017
It is often used when the search space is discrete (e.g., all tours that visit a given set of cities). For problems where finding an approximate global optimum is more important than finding a precise local optimum in a fixed amount of time, simulated annealing may be preferable to alternatives such as gradient descent...
# Perform the simmulated annealing. # Display the final validation. We show all of the iris data as well as the predicted species. # Compute the output from the RBF network # Decode the three output neurons into a class number and print it
_____no_output_____
MIT
code/UnsupervisedNeuralComputation.ipynb
caxenie/basecamp-winterschool-2017
Vector Quantization Vector quantization (VQ) is a form of competitive learning. Such an algorithm is able to discover structure in the input data. Generally speaking, vector quantization is a form of lossy data compression—lossy in the sense that some information contained in the input data is lost as a result of the ...
import numpy as np import scipy as sp import matplotlib.pyplot as plt from sklearn import cluster from sklearn.utils.testing import SkipTest from sklearn.utils.fixes import sp_version try: face = sp.face(gray=True) except AttributeError: # Newer versions of scipy have face in misc from scipy import misc ...
_____no_output_____
MIT
code/UnsupervisedNeuralComputation.ipynb
caxenie/basecamp-winterschool-2017
Plot the results of the clutering and plot the original, quatized, and histogram.
# original face plt.figure(1, figsize=(3, 2.2)) plt.imshow(face, cmap=plt.cm.gray, vmin=vmin, vmax=256) # compressed face plt.figure(2, figsize=(3, 2.2)) plt.imshow(face_compressed, cmap=plt.cm.gray, vmin=vmin, vmax=vmax) # equal bins face regular_values = np.linspace(0, 256, n_clusters + 1) regular_labels = np.searc...
_____no_output_____
MIT
code/UnsupervisedNeuralComputation.ipynb
caxenie/basecamp-winterschool-2017
Assignments In this problem you should group 2d input points (x,y) into clusters and determine the center of each cluster. The number of required clusters is provided as integer number on the first line. Following, the system provides an unknown number of 2d input data points (x, y), one per line. Continue reading unt...
# load the datasets for training and testing import numpy as np import csv with open('./data/vq_3clust_in.txt') as inputfile: train_data = list(csv.reader(inputfile)) with open('./data/vq_3clust_out.txt') as inputfile: test_data = list(csv.reader(inputfile)) # add network code here
_____no_output_____
MIT
code/UnsupervisedNeuralComputation.ipynb
caxenie/basecamp-winterschool-2017
6 cluster VQ![title](img/vq_3clust.png)
# load the datasets for training and testing for the 6 cluster example import numpy as np import csv with open('./data/vq_6clust_in.txt') as inputfile: train_data = list(csv.reader(inputfile)) with open('./data/vq_6clust_out.txt') as inputfile: test_data = list(csv.reader(inputfile)) # add network code he...
_____no_output_____
MIT
code/UnsupervisedNeuralComputation.ipynb
caxenie/basecamp-winterschool-2017
Self-Organizing Maps In neurobiology, during neural growth, synapses are strengthened or weakened, in a process usually modelled as a competition for resources. In such a learning process, there is a competition between the neurons to fire. More precisely, neurons compete with each other (in accordance with a learning...
# Class implementing a basic SOM import scipy.spatial import numpy as np import scipy as sp import sys class SelfOrganizingMap: """ The weights of the output neurons base on the input from the input neurons. """ def __init__(self, input_count, output_count): """ The constructor. ...
_____no_output_____
MIT
code/UnsupervisedNeuralComputation.ipynb
caxenie/basecamp-winterschool-2017
The "Best Matching Unit" or BMU is a very important concept in the training for a SOM. The BMU is the output neuron that has weight connections to the input neurons that most closely match the current input vector. This neuron (and its "neighborhood") are the neurons that will receive training.
# Class implementing the competition stage in SOM, finding the best matching unit. class BestMatchingUnit: """ This class also tracks the worst distance (of all BMU's). This gives some indication of how well the network is trained, and thus becomes the "error" of the entire network. """ def __i...
_____no_output_____
MIT
code/UnsupervisedNeuralComputation.ipynb
caxenie/basecamp-winterschool-2017
In the next section we analyze competitive training, which would be used in a winner-take-all neural network, such as the self organizing map (SOM). This is an unsupervised training method, no ideal data is needed on the training set. If ideal data is provided, it will be ignored. Training is done by looping over all o...
# Class implementing the basic training algorithm for a SOM class BasicTrainSOM: """ Because only the BMU neuron and its close neighbors are updated, you can end up with some output neurons that learn nothing. By default these neurons are not forced to win patterns that are not represented well. This sp...
_____no_output_____
MIT
code/UnsupervisedNeuralComputation.ipynb
caxenie/basecamp-winterschool-2017
A common example used to help teach the principals behind SOMs is the mapping of colours from their three dimensional components - red, green and blue, into two dimensions.The colours are presented to the network as 3D vectors - one dimension for each of the colour components (RGB encoding) - and the network learns to ...
import os import sys from Tkinter import * import numpy as np from neighborhood import * TILES_WIDTH = 50 TILES_HEIGHT = 50 TILE_SCREEN_SIZE = 10 class DisplayColors: def __init__(self,root,samples): # Build the grid display canvas_width = TILES_WIDTH * TILE_SCREEN_SIZE canvas_height = TIL...
Iteration 1, Rate=0.799203, Radius=29 Iteration 2, Rate=0.798406, Radius=28 Iteration 3, Rate=0.797609, Radius=27 Iteration 4, Rate=0.796812, Radius=26 Iteration 5, Rate=0.796015, Radius=25 Iteration 6, Rate=0.795218, Radius=24 Iteration 7, Rate=0.794421, Radius=23 Iteration 8, Rate=0.793624, Radius=22 Iteration 9, Rat...
MIT
code/UnsupervisedNeuralComputation.ipynb
caxenie/basecamp-winterschool-2017
Asignments In this assignment a solution path for the Traveling Salesman Problem (finding a short path to travel once to each city and return home), for an unknown number of cities as input (you can safely assume <= 1000 cities). Each city consists of an ID (an integer number), and X and Y position of that city (two i...
# load the datasets for training and testing for TS in Europe import numpy as np import csv with open('./data/som_ts_in.txt') as inputfile: train_data = list(csv.reader(inputfile)) with open('./data/som_ts_out.txt') as inputfile: test_data = list(csv.reader(inputfile)) # add network code here
_____no_output_____
MIT
code/UnsupervisedNeuralComputation.ipynb
caxenie/basecamp-winterschool-2017
And for a more complex example, consider a more restricted dataset.![title](img/som_ts_random.png)
# load the datasets for training and testing for TS import numpy as np import csv with open('./data/som_ts_in_aux.txt') as inputfile: train_data = list(csv.reader(inputfile)) with open('./data/som_ts_out_aux.txt') as inputfile: test_data = list(csv.reader(inputfile)) # add network code here
_____no_output_____
MIT
code/UnsupervisedNeuralComputation.ipynb
caxenie/basecamp-winterschool-2017
Hopfield Networks Donald Hebb hypothesized in 1949 how neurons are connected with each other in the brain: “When an axon of cell A is near enough to excite a cell B and repeatedly or persistently takes part in firing it, some growth process or metabolic change takes place in one or both cells such that A’s efficiency,...
# Class implementing a Hopfield Network import numpy as np from energetic import EnergeticNetwork class HopfieldNetwork(EnergeticNetwork): def __init__(self, neuron_count): EnergeticNetwork.__init__(self, neuron_count) self.input_count = neuron_count self.output_count = neuron_count ...
_____no_output_____
MIT
code/UnsupervisedNeuralComputation.ipynb
caxenie/basecamp-winterschool-2017
In the next section we implement the Hopefield Network training algorithm![title](img/hopfield_alg.png)
class TrainHopfieldHebbian: def __init__(self, network): self.network = network; self.sum_matrix = np.zeros([network.input_count, network.input_count]) self.pattern_count = 1 def add_pattern(self, pattern): for i in range(self.network.input_count): for j in range(sel...
_____no_output_____
MIT
code/UnsupervisedNeuralComputation.ipynb
caxenie/basecamp-winterschool-2017
In the following sample problem we will implement a Hopfield network to correct distorted patterns (here: 2D images). The algorithm reads a collection of binary images (5 patterns), each image being 10x10 "pixels" in size. A pixel may either be a space ' ' or a circle 'o'. We will train a Hopfield network (size 10x10 n...
# The neural network will learn these patterns. PATTERN = [[ "O O O O O ", " O O O O O", "O O O O O ", " O O O O O", "O O O O O ", " O O O O O", "O O O O O ", " O O O O O", "O O O O O ", " O O O O O"...
_____no_output_____
MIT
code/UnsupervisedNeuralComputation.ipynb
caxenie/basecamp-winterschool-2017
Convert the image representation into a bipolar {-1/1} representation and display according to the original patterns
# Size of the network HEIGHT = 10 WIDTH = 10 def convert_pattern(data, index): result_index = 0 result = np.zeros([WIDTH*HEIGHT]) for row in range(HEIGHT): for col in range(WIDTH): ch = data[index][row][col] result[result_index] = 1 if ch != ' ' else -1 result_i...
Evaluate distorted patterns Convergence for pattern 0 input O O O O O O O O O O O O O O O O O O O O O O O O O attractor O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O ---------------------- Co...
MIT
code/UnsupervisedNeuralComputation.ipynb
caxenie/basecamp-winterschool-2017
In the application of the Hopfield network as a content-addressable memory, we know a priori the fixed points (attractors) of the network in that they correspond to the patterns to be stored. However, the synaptic weights of the network that produce the desired fixed points are unknown, and the problem is how to determ...
TINA -> 6843726 ANTJE -> 8034673 LISA -> 7260915
_____no_output_____
MIT
code/UnsupervisedNeuralComputation.ipynb
caxenie/basecamp-winterschool-2017
Code a Hopfield Network for phonebook learning and restoring using its Content-Addressable-Memory behavior. Simulate network for distorted numbers.The data is represented as: Input | Output Name -> Number TINA -> ? 86'GV | TINA -> 6843726ANTJE -> ?Z!ES-= | ANTJE -> 8034673LISA -> JKXMG | LISA -> 7260915
# add code here
_____no_output_____
MIT
code/UnsupervisedNeuralComputation.ipynb
caxenie/basecamp-winterschool-2017
Simulate network for distorted name.The data is represented as: Input | Output Number -> Name6843726 -> ; 01, | 6843726 -> TINA 8034673 -> &;A$T | 8034673 -> ANTJE7260915 -> N";SE | 7260915 -> LISA
# add code here
_____no_output_____
MIT
code/UnsupervisedNeuralComputation.ipynb
caxenie/basecamp-winterschool-2017
Simulate network for distorted names and numbers.The data is represented as: Input | Output Name -> Number TINE -> 1F&KV]: | TINA -> 6843726ANNJE -> %VZAQ$> | ANTJE -> 8034673RITA -> [)@)EK& | DIVA -> 6060737
# add code here
_____no_output_____
MIT
code/UnsupervisedNeuralComputation.ipynb
caxenie/basecamp-winterschool-2017
2021-05-10 Daily Practice- [x] Practice - [ ] SQL - [x] Algorithms - [ ] Solve + Design- [ ] Learn- [ ] Write- [ ] Build --- Practice- [x] https://leetcode.com/problems/reverse-integer/- [x] https://leetcode.com/problems/longest-common-prefix/- [x] https://leetcode.com/problems/maximum-subarray/- [x] https://leetco...
arr1 = [-1, 3, 8, 2, 9, 5] arr2 = [4, 1, 2, 10, 5, 20] tgt = 24 # Brute-force iterative approach - O(n^2) # Iterate through every pair of elements to find the closest def find_closest_sum(arr1, arr2, tgt): closest = tgt # Can't be further away than the target itself? closest_sums = [] for i, v1 in enumerat...
_____no_output_____
MIT
ds/practice/daily_practice/21-05/21-05-10-130-mon.ipynb
tobias-fyi/vela
Once the simpler version of the problem (where a pair exists that add up to the target) is solved, expand that solution to include any other cases that need to be accounted for (arrays without a pair that add up to the target).In this problem, if the target is not found, add or subtract 1 from the target and try again....
# Sorting the arrays first; start at the top of first array def find_closest_sum(arr1, arr2, tgt): arr1s, arr2s = sorted(arr1), sorted(arr2) # First pair is (arr1s[-1], arr2s[1]) # Increment second array's index # If sum is less than target, increment second array's index # If sum is more than targe...
_____no_output_____
MIT
ds/practice/daily_practice/21-05/21-05-10-130-mon.ipynb
tobias-fyi/vela
Reverse integerOn [LeetCode](https://leetcode.com/problems/reverse-integer/)Given a signed 32-bit integer `x`, return `x` with its digits reversed. If reversing `x` causes the value to go outside the signed 32-bit integer range ``[-2^31, 2^31 - 1]``, then return `0`.Assume the environment does not allow you to store 6...
# Get components of integer 201 -> 102 # Modulo of 10 will return the ten factor - rightmost number 201 % 10 -> 1 # Remove that digit from the integer by floor division 201 // 10 -> 20 # 20 is going to be fed back into function; repeat steps above 20 % 10 -> 0 20 // 10 -> 2 # Base case: 2 % 10 = 2 # Then return tha...
_____no_output_____
MIT
ds/practice/daily_practice/21-05/21-05-10-130-mon.ipynb
tobias-fyi/vela
Longest common prefixOn [LeetCode](https://leetcode.com/problems/longest-common-prefix/)Write a function to find the longest common prefix string amongst an array of strings.If there is no common prefix, return an empty string "". - Implement a trie- Insert words into trie- DFS for node that has multiple children
class TrieNode: """Node of a trie.""" def __init__(self, char: str): self.char = char # Character held by this node self.is_end = False # End of word self.children = {} # Children: key is char, value is node class Trie: """A trie object.""" def __init__(self): """Ins...
_____no_output_____
MIT
ds/practice/daily_practice/21-05/21-05-10-130-mon.ipynb
tobias-fyi/vela
Max SubarrayOn [LeetCode](https://leetcode.com/problems/maximum-subarray/)Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.Example 1: Input: nums = [-2,1,-3,4,-1,2,1,-5,4] Output: 6 Explanation: [4,-1,2,1] has the largest s...
def max_subarray(nums): # vars to hold subarray and max sum so far max_sum = None sub = [] for i, num in enumerate(nums): # iterate through nums # check if the current value is better than the highest sum of all possible combinations of previous values if num >= sum(sub) + num: # if it...
6 1 23
MIT
ds/practice/daily_practice/21-05/21-05-10-130-mon.ipynb
tobias-fyi/vela
Same TreeOn [LeetCode](https://leetcode.com/problems/same-tree/)Given the roots of two binary trees p and q, write a function to check if they are the same or not.Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
class Solution: def preorderTraversal(self, node) -> list: # Base case: node is None if node is None: return [None] # Recursive case: [this node.val, pt(left.val), pt.right.val] return [node.val] + self.preorderTraversal(node.left) + self.preorderTraversal(node.right) def is...
_____no_output_____
MIT
ds/practice/daily_practice/21-05/21-05-10-130-mon.ipynb
tobias-fyi/vela
Combination Sum (Again)
class Solution: def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: valid_paths = [] self.pathSearch(candidates, 0, target, [], valid_paths) return valid_paths def pathSearch(self, candidates, start, target, path, valid_paths): # Base case: targe...
_____no_output_____
MIT
ds/practice/daily_practice/21-05/21-05-10-130-mon.ipynb
tobias-fyi/vela
Data Structures Review LinkedListSingly linked list with recursive methods.
class LinkedListNode: def __init__(self, data=None, next=None): self.data = data self.next = next def append(self, data) -> None: if self.next is None: # Base case, no next node self.next = LinkedListNode(data) else: self.next.append(data) class Linked...
1 2 3
MIT
ds/practice/daily_practice/21-05/21-05-10-130-mon.ipynb
tobias-fyi/vela
QueueFIFO!- Enqueue: constant time - `O(1)`- Dequeue: constant time - `O(1)`- Peek: constant time - `O(1)`- Space complexity = `O(n)`
class Queue: def __init__(self): self.front = None self.back = None def is_empty(self) -> bool: if self.front is None: return True else: return False def enqueue(self, data): new_node = LinkedListNode(data) if self.is_empty(): ...
_____no_output_____
MIT
ds/practice/daily_practice/21-05/21-05-10-130-mon.ipynb
tobias-fyi/vela
StackLIFO!- Push: constant time - `O(1)`- Pop: constant time - `O(1)`- Peek: constant time - `O(1)`- Space complexity = `O(n)`
class Stack: def __init__(self): self.top = None def push(self, data): """Adds element to top of stack.""" new_node = LinkedListNode(data) new_node.next = self.top self.top = new_node def pop(self): """Removes element from top of stack and returns its value....
_____no_output_____
MIT
ds/practice/daily_practice/21-05/21-05-10-130-mon.ipynb
tobias-fyi/vela
Binary Search TreeFirst, I'm going to implement a BST from scratch, run DFS and BFS on it, then look for a good leetcode problem to apply it to.
import math # Perfect binary tree math # Given 127 nodes, what is the height? print(math.log(127 + 1, 2)) # Given height of 8, how many nodes does it have? print(2 ** 8 - 1) class BSTNode: def __init__(self, val: int): self.val = val self.left = None self.right = None def __str__(self...
_____no_output_____
MIT
ds/practice/daily_practice/21-05/21-05-10-130-mon.ipynb
tobias-fyi/vela
Traversals- Breadth-first- Depth-first - Inorder: Node visited in order (l->n->r) - Preorder: Node visited before children (n->l->r) - Postorder: Node visited after children (l->r->n)
from collections import deque def breadth_first_traversal(root): if root is None: return [] results = [] q = deque() q.append(root) while len(q) > 0: node = q.popleft() results.append(node.val) # Put children into the queue if node.left: q.append(node.left)...
_____no_output_____
MIT
ds/practice/daily_practice/21-05/21-05-10-130-mon.ipynb
tobias-fyi/vela
Longest substring without repeating charactersOn [LeetCode](https://leetcode.com/problems/longest-substring-without-repeating-characters/)I believe I have a good method for solving this one now: using a queue as a way to set up a sliding window. I can iterate through the string, adding each character to the queue. If ...
from collections import deque class Solution: def lengthOfLongestSubstring(self, s: str) -> int: max = 0 # Keep track of max queue length q = deque() # Use queue as sliding window for char in s: # Iterate through string # If char being added matches that at front of queue, de...
_____no_output_____
MIT
ds/practice/daily_practice/21-05/21-05-10-130-mon.ipynb
tobias-fyi/vela
View source on GitHub Notebook Viewer Run in Google Colab ConvolutionsTo perform linear convolutions on images, use `image.convolve()`. The only argument to convolve is an `ee.Kernel` which is specified by a shape and the weights in the kernel. Each pixel of the image output by `convolve()` is the linear c...
# Installs geemap package import subprocess try: import geemap except ImportError: print('geemap package not installed. Installing ...') subprocess.check_call(["python", '-m', 'pip', 'install', 'geemap']) # Checks whether this notebook is running on Google Colab try: import google.colab import gee...
_____no_output_____
MIT
tutorials/Image/06_convolutions.ipynb
ppoon23/geemap
Create an interactive map The default basemap is `Google Satellite`. [Additional basemaps](https://github.com/giswqs/geemap/blob/master/geemap/geemap.pyL13) can be added using the `Map.add_basemap()` function.
Map = emap.Map(center=[40, -100], zoom=4) Map.add_basemap('ROADMAP') # Add Google Map Map
_____no_output_____
MIT
tutorials/Image/06_convolutions.ipynb
ppoon23/geemap
Add Earth Engine Python script
# Load and display an image. image = ee.Image('LANDSAT/LC08/C01/T1_TOA/LC08_044034_20140318') Map.setCenter(-121.9785, 37.8694, 11) Map.addLayer(image, {'bands': ['B5', 'B4', 'B3'], 'max': 0.5}, 'input image') # Define a boxcar or low-pass kernel. # boxcar = ee.Kernel.square({ # 'radius': 7, 'units': 'pixels', 'norm...
_____no_output_____
MIT
tutorials/Image/06_convolutions.ipynb
ppoon23/geemap
The output of convolution with the low-pass filter should look something like Figure 1. Observe that the arguments to the kernel determine its size and coefficients. Specifically, with the `units` parameter set to pixels, the `radius` parameter specifies the number of pixels from the center that the kernel will cover. ...
Map = emap.Map(center=[40, -100], zoom=4) # Define a Laplacian, or edge-detection kernel. laplacian = ee.Kernel.laplacian8(1, False) # Apply the edge-detection kernel. edgy = image.convolve(laplacian) Map.addLayer(edgy, {'bands': ['B5', 'B4', 'B3'], 'max': 0.5}, 'edges') Map.setCenter(-121.9785, 37.8694, 11) Map.addL...
_____no_output_____
MIT
tutorials/Image/06_convolutions.ipynb
ppoon23/geemap
Note the format specifier in the visualization parameters. Earth Engine sends display tiles to the Code Editor in JPEG format for efficiency, however edge tiles are sent in PNG format to handle transparency of pixels outside the image boundary. When a visual discontinuity results, setting the format to PNG results in a...
# Create a list of weights for a 9x9 kernel. list = [1, 1, 1, 1, 1, 1, 1, 1, 1] # The center of the kernel is zero. centerList = [1, 1, 1, 1, 0, 1, 1, 1, 1] # Assemble a list of lists: the 9x9 kernel weights as a 2-D matrix. lists = [list, list, list, list, centerList, list, list, list, list] # Create the kernel from t...
_____no_output_____
MIT
tutorials/Image/06_convolutions.ipynb
ppoon23/geemap