init
This commit is contained in:
10
bin/audioswitch
Executable file
10
bin/audioswitch
Executable file
@ -0,0 +1,10 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
CARD=$(pactl list cards short | grep '1f.3' | awk '{print $2}')
|
||||||
|
CURRENT_SINK=$(pactl info | grep "Default Sink:")
|
||||||
|
if [[ "$CURRENT_SINK" == *"iec958"* ]]; then
|
||||||
|
pactl set-card-profile $CARD output:analog-stereo
|
||||||
|
notify-send "analog out active" -i :
|
||||||
|
else
|
||||||
|
pactl set-card-profile $CARD output:iec958-stereo
|
||||||
|
notify-send "digital out active" -i :
|
||||||
|
fi
|
||||||
2
bin/autoclick
Executable file
2
bin/autoclick
Executable file
@ -0,0 +1,2 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
xdotool click --repeat 32 --delay 50 1
|
||||||
13
bin/backup
Executable file
13
bin/backup
Executable file
@ -0,0 +1,13 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
echo "backup starting at $(date)"
|
||||||
|
echo "backing up music and tank to toshiba_mirror"
|
||||||
|
rsync -aP /wdraidz/media/music/ /toshiba-mirror/backups/media/music/ >> /var/log/rsync.log
|
||||||
|
echo "music up to date..."
|
||||||
|
rsync -aP /wdraidz/tank/ /toshiba-mirror/backups/tank/ >> /var/log/rsync.log
|
||||||
|
echo "tank up to date..."
|
||||||
|
echo "backing up wdraidz to seastripe"
|
||||||
|
rsync -aP /wdraidz/media/ /seastripe/backups/wdraidz/media/ >> /var/log/rsync.log
|
||||||
|
echo "media to seastripe done"
|
||||||
|
rsync -aP /wdraidz/tank/ /seastripe/backups/wdraidz/tank/ >> /var/log/rsync.log
|
||||||
|
echo "tank to seastripe done"
|
||||||
|
echo "done."
|
||||||
2
bin/bgselect
Executable file
2
bin/bgselect
Executable file
@ -0,0 +1,2 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
feh --no-fehbg --bg-fill ~/.images/$(ls ~/.images/ | dmenu -c -l 10)
|
||||||
4
bin/bgshuffle
Executable file
4
bin/bgshuffle
Executable file
@ -0,0 +1,4 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
while true; do
|
||||||
|
feh --no-fehbg --bg-fill ~/.images/$(ls ~/.images | shuf -n 1)
|
||||||
|
done
|
||||||
2
bin/browser
Executable file
2
bin/browser
Executable file
@ -0,0 +1,2 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
chromium
|
||||||
5
bin/calculator
Executable file
5
bin/calculator
Executable file
@ -0,0 +1,5 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
EXPRESSION=$(printf "" | dmenu -b -w $(xdotool getactivewindow) -p "calculator")
|
||||||
|
RESULT=$(qalc $EXPRESSION)
|
||||||
|
printf "" | dmenu -b -w $(xdotool getactivewindow) -p "$RESULT"
|
||||||
|
echo $RESULT | sed 's/^[^=≈]*[=≈]//' | xclip -selection clipboard
|
||||||
8
bin/displayctl
Executable file
8
bin/displayctl
Executable file
@ -0,0 +1,8 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
DISPLAY_STATUS=$(xrandr | grep DP-4)
|
||||||
|
|
||||||
|
if [[ "$DISPLAY_STATUS" == *"1440x3440"* ]]; then
|
||||||
|
xrandr --output DP-4 --off
|
||||||
|
else
|
||||||
|
init_displays
|
||||||
|
fi
|
||||||
22
bin/gsr
Executable file
22
bin/gsr
Executable file
@ -0,0 +1,22 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
GSRPID=$(pidof gpu-screen-recorder)
|
||||||
|
DWMBLOCKSPID=$(pidof dwmblocks)
|
||||||
|
|
||||||
|
if [[ -n $GSRPID ]]; then
|
||||||
|
kill -n 2 $GSRPID
|
||||||
|
kill -n 36 $DWMBLOCKSPID
|
||||||
|
notify-send "recording saved" -i :
|
||||||
|
exit
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ $1 == 1 ]]; then
|
||||||
|
gpu-screen-recorder -w DP-0 -k hevc -c mkv -f 60 -bm cbr -q 12000 -ac opus -a "default_output" \
|
||||||
|
-o "$HOME/wdraidz/media/game-videos/$(date +%m-%d-%Y_%R:%S).mkv"&
|
||||||
|
kill -n 36 $DWMBLOCKSPID
|
||||||
|
notify-send "recording started with no mic" -i :
|
||||||
|
else
|
||||||
|
gpu-screen-recorder -w DP-0 -k hevc -c mkv -f 60 -bm cbr -q 12000 -ac opus -a "default_output|default_input" \
|
||||||
|
-o "$HOME/wdraidz/media/game-videos/$(date +%m-%d-%Y_%R:%S).mkv"&
|
||||||
|
kill -n 36 $DWMBLOCKSPID
|
||||||
|
notify-send "recording started" -i :
|
||||||
|
fi
|
||||||
10
bin/int_display_refresh-rate
Executable file
10
bin/int_display_refresh-rate
Executable file
@ -0,0 +1,10 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
LOW="xrandr --output eDP-1 --mode 2560x1600 --rate 60"
|
||||||
|
HIGH="xrandr --output eDP-1 --mode 2560x1600 --rate 165"
|
||||||
|
CHOICE=$(printf "165Hz\n60Hz" | dmenu -c -i -l 2 -p "choose refresh rate:")
|
||||||
|
case $CHOICE in
|
||||||
|
"165Hz")
|
||||||
|
$HIGH;;
|
||||||
|
"60Hz")
|
||||||
|
$LOW;;
|
||||||
|
esac
|
||||||
26
bin/manager
Executable file
26
bin/manager
Executable file
@ -0,0 +1,26 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
CORE="suspend\nsuspend in 5 minutes\nreboot\nshutdown\n"
|
||||||
|
EXTRA="sync music\nAIO pump speed\nkey repeat rate\nfan curve\nvolume mixer"
|
||||||
|
|
||||||
|
ACTION=$(printf "$CORE$EXTRA" | dmenu -c -i -l 10 -p "manager")
|
||||||
|
|
||||||
|
case "$ACTION" in
|
||||||
|
"suspend")
|
||||||
|
systemctl suspend;;
|
||||||
|
"suspend in 5 minutes")
|
||||||
|
sleep 300;systemctl suspend;;
|
||||||
|
"reboot")
|
||||||
|
systemctl reboot;;
|
||||||
|
"shutdown")
|
||||||
|
systemctl poweroff;;
|
||||||
|
"fan curve")
|
||||||
|
liquidctl_fan-curve;;
|
||||||
|
"key repeat rate")
|
||||||
|
xset r rate 200 40;;
|
||||||
|
"AIO pump speed")
|
||||||
|
set_pump_speed;;
|
||||||
|
"volume mixer")
|
||||||
|
st -i -g 60x20-200+200 -e pulsemixer;;
|
||||||
|
"sync music")
|
||||||
|
sync_music;;
|
||||||
|
esac
|
||||||
5
bin/multi_unzip
Executable file
5
bin/multi_unzip
Executable file
@ -0,0 +1,5 @@
|
|||||||
|
for file in ./*.zip; do
|
||||||
|
dir_name=${file%.*}
|
||||||
|
mkdir -p "$dir_name"
|
||||||
|
unzip -d "$dir_name" "$file"
|
||||||
|
done
|
||||||
77
bin/nmap
Executable file
77
bin/nmap
Executable file
@ -0,0 +1,77 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# (c) CompuMatter, LLC, ServerMatter
|
||||||
|
# no warranty expressed or implied - use as is.
|
||||||
|
# purpose of this script:
|
||||||
|
# Can't use angryipscanner from a command line and haven't been able to find anything else that gives you what you're looking for?
|
||||||
|
# This nmap based bash script might just be what you're looking for.
|
||||||
|
|
||||||
|
if ! which nmap >/dev/null; then
|
||||||
|
echo "nmap is not installed - this script requires it"
|
||||||
|
echo "It can be installed with - apt install nmap"
|
||||||
|
return;
|
||||||
|
fi
|
||||||
|
# Check if the script is being run as root (EUID = 0)
|
||||||
|
if [ "$EUID" -ne 0 ]; then
|
||||||
|
echo "This script must be run as root user or with sudo"
|
||||||
|
return;
|
||||||
|
fi
|
||||||
|
lease_file_location="/var/lib/dhcp/dhcpd.leases"
|
||||||
|
|
||||||
|
# will return br0, eth0, eno1 or whatever the default Interface is
|
||||||
|
default_interface=$(ip route | awk '/default/ {print $5}')
|
||||||
|
ip_and_cidr=$(ip -o -f inet addr show $default_interface | awk '{print $4}')
|
||||||
|
ip_range=$(echo $ip_and_cidr | sed 's/\.[0-9]*\//.0\//')
|
||||||
|
|
||||||
|
echo -e "\nRunning nmap -sn $ip_range to get a list of all IP addresses\n"
|
||||||
|
readarray -t ips < <(nmap -sn $ip_range | awk '/Nmap scan report/{gsub(/[()]/,""); print $NF}' | sort -t . -n -k 1,1 -k 2,2 -k 3,3 -k 4,4)
|
||||||
|
|
||||||
|
# Set column widths
|
||||||
|
col1=14
|
||||||
|
col2=17
|
||||||
|
col3=17
|
||||||
|
col4=15
|
||||||
|
col5=30
|
||||||
|
|
||||||
|
echo -e "Checking each IP address for Hostname, MAC, Workgroup or Domain, Manufacturer info\n"
|
||||||
|
|
||||||
|
# Format the output
|
||||||
|
printf "%-${col1}s | %-${col2}s | %-${col3}s | %-${col4}s | %-${col5}s \n" "IP" "MAC" "HOSTNAME" "WG-DOMAIN" "MANUFACTURER"
|
||||||
|
printf "%-${col1}s | %-${col2}s | %-${col3}s | %-${col4}s | %-${col5}s \n" "$(printf '%.s-' {1..13})" "$(printf '%.s-' {1..17})" "$(printf '%.s-' {1..17})" "$(printf '%.s-' {1..15})" "$(printf '%.s-' {1..30})"
|
||||||
|
|
||||||
|
for IP in "${ips[@]}"
|
||||||
|
do
|
||||||
|
# Run the nmap command for the current IP
|
||||||
|
OUTPUT="$(nmap --script nbstat.nse -p 137,139 $IP)"
|
||||||
|
# Extract the necessary information
|
||||||
|
MAC=$(echo "$OUTPUT" | grep 'MAC Address' | awk '{print $3}')
|
||||||
|
HOSTNAME=$(echo "$OUTPUT" | grep '<20>.*<unique>.*<active>' | awk -F'[|<]' '{print $2}' | tr -d '_' | xargs)
|
||||||
|
WG_DOMAIN=$(echo "$OUTPUT" | grep -v '<permanent>' | grep '<00>.*<group>.*<active>' | awk -F'[|<]' '{print $2}' | tr -d '_' | xargs)
|
||||||
|
MANUFACTURER=$(echo "$OUTPUT" | grep 'MAC Address' | awk -F'(' '{print $2}' | cut -d ')' -f1)
|
||||||
|
|
||||||
|
# if a dhcp server leases file exists on this machine, we will query it for a hostname if not already returned by nmap
|
||||||
|
if [ -f "$lease_file_location" ]; then
|
||||||
|
# If HOSTNAME is empty, fetch from dhcpd.leases
|
||||||
|
if [ -z "$HOSTNAME" ]; then
|
||||||
|
HOSTNAME=$(awk -v ip="$IP" '$1 == "lease" && $2 == ip {f=1} f && /client-hostname/ {print substr($2, 2, length($2) - 3); exit}' "$lease_file_location" | cut -c 1-15)
|
||||||
|
|
||||||
|
# Append an asterisk (*) if HOSTNAME has a value
|
||||||
|
if [ -n "$HOSTNAME" ]; then
|
||||||
|
HOSTNAME="$HOSTNAME *"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Print a row of data for the current IP
|
||||||
|
printf "%-${col1}s | %-${col2}s | %-${col3}s | %-${col4}s | %-${col5}s \n" "$IP" "$MAC" "$HOSTNAME" "$WG_DOMAIN" "$MANUFACTURER"
|
||||||
|
done
|
||||||
|
|
||||||
|
if [ -f "$lease_file_location" ]; then
|
||||||
|
echo -e "\n* to the right of hostname indicates the hostname could not be acquired from nmap so was pulled from $lease_file_location\n"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# we are grateful if you would leave our short tagline attached
|
||||||
|
echo -e "This network scanner script is provided free of charge by ServerMatter\n"
|
||||||
|
# Disclaimer: This script is provided as-is with no warranty and no responsibility.
|
||||||
|
# The author and contributors shall not be liable for any direct, indirect, incidental,
|
||||||
|
# special, exemplary, or consequential damages arising from the use of this script.
|
||||||
|
|
||||||
4
bin/open
Executable file
4
bin/open
Executable file
@ -0,0 +1,4 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
DIR=$(ls $HOME | dmenu -c -i -l 10 -p "choose dir")
|
||||||
|
FILE=$(ls $HOME/$DIR| dmenu -c -i -l 10 -p "file to open")
|
||||||
|
xdg-open $HOME/$DIR/"$FILE"
|
||||||
8
bin/playerctl-mon
Executable file
8
bin/playerctl-mon
Executable file
@ -0,0 +1,8 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
playerctl --follow metadata title |
|
||||||
|
while read x; do
|
||||||
|
dunstctl close-all
|
||||||
|
TITLE=$(playerctl metadata title)
|
||||||
|
ARTIST=$(playerctl metadata artist)
|
||||||
|
notify-send "$TITLE" "$ARTIST" -i :
|
||||||
|
done
|
||||||
12
bin/pull_all
Executable file
12
bin/pull_all
Executable file
@ -0,0 +1,12 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
for repo in ./*/; do
|
||||||
|
(
|
||||||
|
cd "$repo" || exit
|
||||||
|
git pull
|
||||||
|
cd -
|
||||||
|
) > /dev/null 2<&1 &
|
||||||
|
done
|
||||||
|
|
||||||
|
wait
|
||||||
|
|
||||||
|
echo "done"
|
||||||
15
bin/record
Executable file
15
bin/record
Executable file
@ -0,0 +1,15 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
SCREEN="ffmpeg -s 3440x1440 -f x11grab -r 60 -i :0.0+0,0"
|
||||||
|
SYSTEM_AUDIO="-f pulse -i alsa_output.pci-0000_00_1f.3.iec958-stereo.monitor"
|
||||||
|
MICROPHONE="-f pulse -i default:monitor"
|
||||||
|
COMPRESSION="-c:a flac -c:v hevc_nvenc -b:v 12M"
|
||||||
|
FILENAME="$HOME/wdraidz/media/game-videos/$(date +%m-%d-%Y_%R:%S).mkv"
|
||||||
|
SIGSEND="kill -n 36 $(pidof dwmblocks)"
|
||||||
|
|
||||||
|
if [[ $1 == 1 ]]; then
|
||||||
|
$SCREEN $SYSTEM_AUDIO $MICROPHONE -filter_complex "[1:0][2:0]amerge=inputs=2[a]" -map 0:v -map "[a]" $COMPRESSION $FILENAME&
|
||||||
|
else
|
||||||
|
$SCREEN $SYSTEM_AUDIO $COMPRESSION $FILENAME&
|
||||||
|
fi
|
||||||
|
|
||||||
|
$SIGSEND
|
||||||
9
bin/run
Executable file
9
bin/run
Executable file
@ -0,0 +1,9 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
mkdir -p "output"
|
||||||
|
TRACK=1
|
||||||
|
for file in *.opus; do
|
||||||
|
NEW_FILENAME=$(echo $file | sed 's/ - Kirby Super Star OST//')
|
||||||
|
TITLE=$(echo $file | sed 's/ - Kirby Super Star OST.opus//')
|
||||||
|
ffmpeg -i "$file" -metadata artist="Nintendo" -metadata album="Kirby Super Star OST" -metadata title="$TITLE" -metadata track="$TRACK" -codec copy "output/$file"
|
||||||
|
((TRACK++))
|
||||||
|
done
|
||||||
7
bin/screenshot
Executable file
7
bin/screenshot
Executable file
@ -0,0 +1,7 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
if [[ $1 == 1 ]]; then
|
||||||
|
SELECTION=$(slop)
|
||||||
|
maim -g $SELECTION ~/pictures/$(date +%m-%d-%Y:%R:%S).png && notify-send "screenshot saved" -i :
|
||||||
|
else
|
||||||
|
maim ~/pictures/$(date +%m-%d-%Y:%R:%S).png && notify-send "screenshot saved" -i :
|
||||||
|
fi
|
||||||
7
bin/st-bat
Executable file
7
bin/st-bat
Executable file
@ -0,0 +1,7 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
VOLTAGE=$(cat /sys/class/power_supply/BAT1/voltage_now)
|
||||||
|
CURRENT=$(cat /sys/class/power_supply/BAT1/current_now)
|
||||||
|
POWER="$(echo "scale=2; $VOLTAGE*$CURRENT/1000000000000" | bc)W"
|
||||||
|
CHARGE="$(cat /sys/class/power_supply/BAT*/capacity)%"
|
||||||
|
echo "$CHARGE $POWER"
|
||||||
|
#echo $POWER >> .power_log
|
||||||
9
bin/st-dbus-mon
Executable file
9
bin/st-dbus-mon
Executable file
@ -0,0 +1,9 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
dbus-monitor --session "member='PropertiesChanged'" |
|
||||||
|
while read X; do
|
||||||
|
if [[ $X == *"Metadata"* ]]; then
|
||||||
|
TITLE=$(playerctl metadata title)
|
||||||
|
ARTIST=$(playerctl metadata artist)
|
||||||
|
notify-send "Now playing" "$TITLE - $ARTIST" -i :
|
||||||
|
fi
|
||||||
|
done
|
||||||
2
bin/st-disk
Executable file
2
bin/st-disk
Executable file
@ -0,0 +1,2 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
echo $(df / | awk 'NR==2 {print $6" "$5}')
|
||||||
9
bin/st-mem
Executable file
9
bin/st-mem
Executable file
@ -0,0 +1,9 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
|
||||||
|
MEMORY_USED=$(free -m | gawk 'NR==2 {print $3}')
|
||||||
|
if [ $MEMORY_USED -gt 1024 ]; then
|
||||||
|
MEMORY_USED="$(echo "scale=1; $MEMORY_USED / 1024" | bc)G"
|
||||||
|
else
|
||||||
|
MEMORY_USED="$MEMORY_USEDM"
|
||||||
|
fi
|
||||||
|
echo $MEMORY_USED
|
||||||
8
bin/st-power
Executable file
8
bin/st-power
Executable file
@ -0,0 +1,8 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
POWER="$(pwrstat -status | grep "Load" | awk '{print $2}')W"
|
||||||
|
CHARGE=$(pwrstat -status | grep "Battery Capacity" | awk '{print $3$4}')
|
||||||
|
if [[ "$CHARGE" == "100%" ]]; then
|
||||||
|
echo $POWER
|
||||||
|
else
|
||||||
|
echo "$CHARGE $POWER"
|
||||||
|
fi
|
||||||
8
bin/st-rec
Executable file
8
bin/st-rec
Executable file
@ -0,0 +1,8 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
sleep 1
|
||||||
|
PID=$(pidof ffmpeg)
|
||||||
|
if [ -n "$PID" ]; then
|
||||||
|
echo " REC"
|
||||||
|
elif [ -z "$PID" ]; then
|
||||||
|
echo " IDLE"
|
||||||
|
fi
|
||||||
4
bin/st-temp
Executable file
4
bin/st-temp
Executable file
@ -0,0 +1,4 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
CPUTEMP=$(sensors | grep "Package id 0" | awk '{print $4}' | sed s/+// )
|
||||||
|
COOLANT_TEMP=$(liquidctl status | grep "Liquid temperature" | awk '{print $4$5}')
|
||||||
|
echo "$CPUTEMP // $COOLANT_TEMP"
|
||||||
7
bin/st-vol
Executable file
7
bin/st-vol
Executable file
@ -0,0 +1,7 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
VOLUME=$(wpctl get-volume @DEFAULT_SINK@)
|
||||||
|
if [[ $VOLUME =~ "MUTED" ]]; then
|
||||||
|
echo " MUTED"
|
||||||
|
fi
|
||||||
|
VOLUME=$(echo $VOLUME | sed s/"Volume: 0."//g)
|
||||||
|
echo "$VOLUME%"
|
||||||
15
bin/status
Executable file
15
bin/status
Executable file
@ -0,0 +1,15 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
|
||||||
|
while true; do
|
||||||
|
BATTERY="$(cat /sys/class/power_supply/BAT1/capacity)%"
|
||||||
|
MEMORY_USED="$(free -m | awk 'NR==2 {print $3}')"
|
||||||
|
VOLUME=$(wpctl get-volume @DEFAULT_SINK@)
|
||||||
|
DATE_TIME=$(date +%m-%d-%Y" "%R:%S)
|
||||||
|
if [ "$MEMORY_USED" -gt 4096 ]; then
|
||||||
|
MEMORY_USED="$((MEMORY_USED/1024)) GiB"
|
||||||
|
else
|
||||||
|
MEMORY_USED="$MEMORY_USED MiB"
|
||||||
|
fi
|
||||||
|
xsetroot -name "$BATTERY $MEMORY_USED $VOLUME $DATE_TIME"
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
7
bin/sync_music
Executable file
7
bin/sync_music
Executable file
@ -0,0 +1,7 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
rsync -aP $HOME/wdraidz/media/music/ $HOME/music/ > $HOME/.sync_log && SUCCESS=1
|
||||||
|
if [[ $SUCCESS == 1 ]]; then
|
||||||
|
notify-send "sync complete; logged to $HOME/.sync_log" -i :
|
||||||
|
else
|
||||||
|
notify-send "sync error..." -i :
|
||||||
|
fi
|
||||||
12
bin/volumectl
Executable file
12
bin/volumectl
Executable file
@ -0,0 +1,12 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
INCREMENT="2"
|
||||||
|
|
||||||
|
if [[ "$1" == "up" ]]; then
|
||||||
|
wpctl set-volume @DEFAULT_SINK@ $INCREMENT%+
|
||||||
|
elif [[ "$1" == "down" ]]; then
|
||||||
|
wpctl set-volume @DEFAULT_SINK@ $INCREMENT%-
|
||||||
|
elif [[ "$1" == "mute" ]]; then
|
||||||
|
wpctl set-mute @DEFAULT_SINK@ toggle
|
||||||
|
fi
|
||||||
|
|
||||||
|
kill -n 35 $(pidof dwmblocks)
|
||||||
1
c/baller.h
Normal file
1
c/baller.h
Normal file
@ -0,0 +1 @@
|
|||||||
|
static char BALLER[] = "baller";
|
||||||
5
c/bungus.c
Normal file
5
c/bungus.c
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
printf("boner\n");
|
||||||
|
}
|
||||||
10
c/calculator.c
Normal file
10
c/calculator.c
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
printf("input expression: ");
|
||||||
|
char input[16];
|
||||||
|
fgets(input,16,stdin);
|
||||||
|
printf("input: %s",input);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
18
c/factorial.c
Normal file
18
c/factorial.c
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
|
long fact(long n) {
|
||||||
|
if (n == 0) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
else return(n*fact(n-1));
|
||||||
|
}
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
printf("enter a POSITIVE integer... ");
|
||||||
|
long input;
|
||||||
|
scanf("%d", &input);
|
||||||
|
long output = fact(input);
|
||||||
|
printf("output: %lld\n", output);
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
7
c/head.c
Normal file
7
c/head.c
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
#include <stdio.h>
|
||||||
|
#include "baller.h"
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
printf("%s\n", BALLER);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
18
c/key.c
Normal file
18
c/key.c
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
#include <ncurses.h>
|
||||||
|
int main() {
|
||||||
|
initscr();
|
||||||
|
cbreak();
|
||||||
|
noecho();
|
||||||
|
|
||||||
|
printw("press h to do something, and q to quit.\n");
|
||||||
|
|
||||||
|
int ch;
|
||||||
|
while ((ch = getch()) != 'q') {
|
||||||
|
if (ch == 'h') {
|
||||||
|
printw("yep thats h\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
endwin();
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
18
c/ncurses.c
Normal file
18
c/ncurses.c
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
#include <ncurses.h>
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
initscr();
|
||||||
|
start_color();
|
||||||
|
|
||||||
|
mvprintw(20, 20, "baller");
|
||||||
|
|
||||||
|
refresh();
|
||||||
|
|
||||||
|
getch();
|
||||||
|
clear();
|
||||||
|
mvprintw(10,30, "baller2");
|
||||||
|
getch();
|
||||||
|
|
||||||
|
endwin();
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
26
c/opengl.c
Normal file
26
c/opengl.c
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
#include <GLFW/glfw3.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
glfwInit();
|
||||||
|
|
||||||
|
GLFWwindow* window = glfwCreateWindow(400, 400, "baller", NULL, NULL);
|
||||||
|
glfwMakeContextCurrent(window);
|
||||||
|
|
||||||
|
while (!glfwWindowShouldClose(window)) {
|
||||||
|
glClear(GL_COLOR_BUFFER_BIT);
|
||||||
|
|
||||||
|
glBegin(GL_QUADS);
|
||||||
|
glVertex2f(-0.5f, -0.5f);
|
||||||
|
glVertex2f( 0.5f, -0.5f);
|
||||||
|
glVertex2f( 0.5f, 0.5f);
|
||||||
|
glVertex2f(-0.5f, 0.5f);
|
||||||
|
glEnd();
|
||||||
|
|
||||||
|
glfwSwapBuffers(window);
|
||||||
|
glfwPollEvents();
|
||||||
|
}
|
||||||
|
|
||||||
|
glfwTerminate();
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
9
c/pointers.c
Normal file
9
c/pointers.c
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
int x = 8;
|
||||||
|
int *point = &x;
|
||||||
|
int **pointpoint = &point;
|
||||||
|
printf("x: %d\n", **pointpoint);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
11
c/print.c
Normal file
11
c/print.c
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
// char string[21] = "this is a char array";
|
||||||
|
for (float i = 0; i < 100; i += 0.0001) {
|
||||||
|
// printf(string);
|
||||||
|
printf("number incoming: %f\n",i);
|
||||||
|
// printf("\n");
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
13
c/sig.c
Normal file
13
c/sig.c
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
#include <stdio.h>
|
||||||
|
#include <signal.h>
|
||||||
|
//#include <unistd.h>
|
||||||
|
|
||||||
|
void handlesig36(int sig) {
|
||||||
|
printf("received signal %d\n", sig);
|
||||||
|
}
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
signal(SIGRTMIN+2, handlesig36);
|
||||||
|
//while (1);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
49
c/structs.c
Normal file
49
c/structs.c
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
#include <stdio.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
struct dog {
|
||||||
|
int age;
|
||||||
|
int weight;
|
||||||
|
char color[16];
|
||||||
|
char name[16];
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
void menu(struct dog atlas) {
|
||||||
|
int option;
|
||||||
|
|
||||||
|
do {
|
||||||
|
printf("dawg\n");
|
||||||
|
printf("1. Option 1\n");
|
||||||
|
printf("2. Option 2\n");
|
||||||
|
printf("3. Option 3\n");
|
||||||
|
printf("4. Exit\n");
|
||||||
|
scanf("%d", &option);
|
||||||
|
|
||||||
|
switch (option) {
|
||||||
|
case 1:
|
||||||
|
printf("name: %s\n", atlas.name);
|
||||||
|
break;
|
||||||
|
case 2:
|
||||||
|
printf("age: %d\n", atlas.age);
|
||||||
|
break;
|
||||||
|
case 4:
|
||||||
|
printf("exiting...\n");
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
printf("Invalid option\n");
|
||||||
|
}
|
||||||
|
} while (option != 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
struct dog atlas;
|
||||||
|
atlas.age = 7;
|
||||||
|
atlas.weight = 77;
|
||||||
|
strcpy(atlas.color, "black");
|
||||||
|
strcpy(atlas.name, "atlas");
|
||||||
|
|
||||||
|
menu(atlas);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
29
c/webserver.c
Normal file
29
c/webserver.c
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
#include <sys/socket.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <fcntl.h>
|
||||||
|
#include <sys/sendfile.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
#include <netinet/in.h>
|
||||||
|
|
||||||
|
// followed that one guys tutorial. can only send 256 bytes per request
|
||||||
|
void main() {
|
||||||
|
int sock = socket(AF_INET, SOCK_STREAM, 0);
|
||||||
|
struct sockaddr_in addr = {
|
||||||
|
AF_INET,
|
||||||
|
0x901f,
|
||||||
|
0
|
||||||
|
};
|
||||||
|
bind(sock, &addr, sizeof(addr));
|
||||||
|
listen(sock, 32);
|
||||||
|
int client_fd = accept(sock, 0, 0);
|
||||||
|
char buffer[256] = {0};
|
||||||
|
recv(client_fd, buffer, 256, 0);
|
||||||
|
|
||||||
|
char* file = buffer + 5;
|
||||||
|
*strchr(file, ' ') = 0;
|
||||||
|
int opened_fd = open(file, O_RDONLY);
|
||||||
|
sendfile(client_fd, opened_fd, 0, 256);
|
||||||
|
close(opened_fd);
|
||||||
|
close(client_fd);
|
||||||
|
close(sock);
|
||||||
|
}
|
||||||
10
cpp/arrays.cpp
Normal file
10
cpp/arrays.cpp
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
#include <iostream>
|
||||||
|
using namespace std;
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
int numbers[] = {2,4,8,16};
|
||||||
|
for (int number : numbers) {
|
||||||
|
cout << number << endl;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
17
cpp/print.cpp
Normal file
17
cpp/print.cpp
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
#include <iostream>
|
||||||
|
#include <string>
|
||||||
|
using namespace std;
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
int x;
|
||||||
|
string y = "this is stored as a string";
|
||||||
|
cout << "enter 1 to start: ";
|
||||||
|
cin >> x;
|
||||||
|
if (x = 1) {
|
||||||
|
for (float n = 0; n < 10; n += 0.000000001) {
|
||||||
|
cout << n << " " << endl;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
19
cpp/structs.cpp
Normal file
19
cpp/structs.cpp
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
#include <iostream>
|
||||||
|
#include <string>
|
||||||
|
using namespace std;
|
||||||
|
|
||||||
|
struct dog {
|
||||||
|
int age;
|
||||||
|
int weight;
|
||||||
|
string color;
|
||||||
|
string name;
|
||||||
|
};
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
dog atlas;
|
||||||
|
atlas.age = 7;
|
||||||
|
atlas.weight = 77;
|
||||||
|
atlas.color = "black";
|
||||||
|
atlas.name = "Atlas";
|
||||||
|
cout << atlas.color << endl;
|
||||||
|
}
|
||||||
11
go/file_server.go
Normal file
11
go/file_server.go
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// Simple static webserver:
|
||||||
|
log.Fatal(http.ListenAndServe("0.0.0.0:8080", http.FileServer(http.Dir("/home/nik"))))
|
||||||
|
}
|
||||||
71
go/gofs.go
Normal file
71
go/gofs.go
Normal file
@ -0,0 +1,71 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"io/fs"
|
||||||
|
"log"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
|
||||||
|
"github.com/pkg/sftp"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// Parse the command-line arguments
|
||||||
|
if len(os.Args) < 2 {
|
||||||
|
log.Fatalf("Usage: %v [user@domain.com:/directory/i/want/to/mount]", os.Args[0])
|
||||||
|
}
|
||||||
|
remoteAddr := os.Args[1]
|
||||||
|
|
||||||
|
// Connect to the remote server using SFTP
|
||||||
|
sshConfig := &ssh.ClientConfig{
|
||||||
|
User: "username",
|
||||||
|
Auth: []ssh.AuthMethod{
|
||||||
|
ssh.Password("password"),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
conn, err := ssh.Dial("tcp", remoteAddr, sshConfig)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to connect to remote server: %v", err)
|
||||||
|
}
|
||||||
|
client, err := sftp.NewClient(conn)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to create SFTP client: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// List the contents of the remote directory
|
||||||
|
entries, err := client.ReadDir("/path/to/remote/directory")
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to list remote directory: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create a local filesystem for the remote directory
|
||||||
|
fs := os.DirFS("/path/to/local/directory")
|
||||||
|
|
||||||
|
// Add each file from the remote directory to the local filesystem
|
||||||
|
for _, entry := range entries {
|
||||||
|
filename := filepath.Join(fs, entry.Name())
|
||||||
|
if err = fs.MkdirAll(filepath.Dir(filename), 0755); err != nil {
|
||||||
|
log.Fatalf("Failed to create directory: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := client.OpenFile(entry.Name(), os.O_RDONLY, fs); err != nil {
|
||||||
|
log.Fatalf("Failed to open remote file: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mount the local filesystem as a directory in the client's namespace
|
||||||
|
if err = os.MkdirAll("/path/to/mounted/directory", 0755); err != nil {
|
||||||
|
log.Fatalf("Failed to create mount point: %v", err)
|
||||||
|
}
|
||||||
|
if err := syscall.Mount(fs, "/path/to/mounted/directory", "", syscall.MS_RDONLY, ""); err != nil {
|
||||||
|
log.Fatalf("Failed to mount filesystem: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// List the contents of the local directory to verify that it has been mounted correctly
|
||||||
|
entries, err = os.ReadDir("/path/to/mounted/directory")
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to list mounted directory: %v", err)
|
||||||
|
}
|
||||||
|
fmt.Println(entries)
|
||||||
|
}
|
||||||
5
go/hello_world.go
Normal file
5
go/hello_world.go
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
println("hello world!")
|
||||||
|
}
|
||||||
14
go/owm.go
Normal file
14
go/owm.go
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
//weather, err := http.Get("https://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude + "&appid=" + apikey)
|
||||||
|
weather, err := http.Get("https://api.openweathermap.org/data/2.5/weather?lat=47.772&lon=-122.22&appid=0c7757e1fecf8d20a8a385b2be959d98")
|
||||||
|
if err != nil {
|
||||||
|
print(err)
|
||||||
|
}
|
||||||
|
print(weather)
|
||||||
|
}
|
||||||
10
html/index.html
Normal file
10
html/index.html
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<title>apache</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1 align="center">what are you doing here? hmm???</h1>
|
||||||
|
<h2 align="center">append create-smp to the url to download the instance, or click <a href="create-smp.zip">here</a> to get it </h2>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
16
java/Recursion.java
Normal file
16
java/Recursion.java
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
public class Recursion {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
int x = 169;
|
||||||
|
int y = 2;
|
||||||
|
|
||||||
|
System.out.println(recurse(x, y));
|
||||||
|
|
||||||
|
}
|
||||||
|
public static int recurse(int x, int y) {
|
||||||
|
if (x < y) {
|
||||||
|
return x;
|
||||||
|
} else {
|
||||||
|
return recurse(x - y, y);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
14
java/countWords.java
Executable file
14
java/countWords.java
Executable file
@ -0,0 +1,14 @@
|
|||||||
|
import java.io.*;
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
public class countWords {
|
||||||
|
public static void main(String[] args) throws FileNotFoundException {
|
||||||
|
Scanner fileScanner = new Scanner(new File(args[0]));
|
||||||
|
int count = 0;
|
||||||
|
while (fileScanner.hasNext()) {
|
||||||
|
count++;
|
||||||
|
String dummy = fileScanner.next();
|
||||||
|
}
|
||||||
|
System.out.println(count);
|
||||||
|
}
|
||||||
|
}
|
||||||
9
javascript/me learning js.js
Normal file
9
javascript/me learning js.js
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
var yourMother = "Obese";
|
||||||
|
var yourMothersMass = 9000;
|
||||||
|
console.log(yourMother)
|
||||||
|
|
||||||
|
var x = 5;
|
||||||
|
var y = 10;
|
||||||
|
document.getElementById("demo").innerHTML = x + y;
|
||||||
|
|
||||||
|
console.log(document.getElementById("balls").children)
|
||||||
11
lua/test.lua
Normal file
11
lua/test.lua
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
function factorial (i)
|
||||||
|
if i == 0 then
|
||||||
|
return 1
|
||||||
|
else
|
||||||
|
return i * factorial(i-1)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
print("number: ")
|
||||||
|
num = io.read("*number")
|
||||||
|
print(factorial(num))
|
||||||
54422
python/atms-310/datasets/Montreal Daily Weather.csv
Executable file
54422
python/atms-310/datasets/Montreal Daily Weather.csv
Executable file
File diff suppressed because it is too large
Load Diff
BIN
python/atms-310/datasets/air.mon.mean.nc
Executable file
BIN
python/atms-310/datasets/air.mon.mean.nc
Executable file
Binary file not shown.
1000
python/atms-310/datasets/data0001.txt
Executable file
1000
python/atms-310/datasets/data0001.txt
Executable file
File diff suppressed because it is too large
Load Diff
2000
python/atms-310/datasets/data0002.txt
Executable file
2000
python/atms-310/datasets/data0002.txt
Executable file
File diff suppressed because it is too large
Load Diff
3000
python/atms-310/datasets/data0003.txt
Executable file
3000
python/atms-310/datasets/data0003.txt
Executable file
File diff suppressed because it is too large
Load Diff
4
python/atms-310/datasets/test.txt
Executable file
4
python/atms-310/datasets/test.txt
Executable file
@ -0,0 +1,4 @@
|
|||||||
|
This is a test!
|
||||||
|
Here's some information:
|
||||||
|
IMPORTANT THINGS TO KNOW
|
||||||
|
Okay, that's all I got.
|
||||||
22
python/atms-310/homework/homework1.py
Executable file
22
python/atms-310/homework/homework1.py
Executable file
@ -0,0 +1,22 @@
|
|||||||
|
a = 3.0 <= 3.1
|
||||||
|
b = 22 + 11.0
|
||||||
|
c = 11 + int(13)
|
||||||
|
d = 4 != 4
|
||||||
|
e = (3 <= 5) or (5<=4)
|
||||||
|
f = (3 <= 5) and (5 <= 4)
|
||||||
|
|
||||||
|
print(a)
|
||||||
|
print(b)
|
||||||
|
print(c)
|
||||||
|
print(d)
|
||||||
|
print(e)
|
||||||
|
print(f)
|
||||||
|
|
||||||
|
c = {'building number': '7725',
|
||||||
|
'street name': '188th Ave NE',
|
||||||
|
'city': 'Redmond',
|
||||||
|
'state': 'Washington',
|
||||||
|
'zip code' : 98052}
|
||||||
|
|
||||||
|
print('redmond costco is located at:')
|
||||||
|
print(c['building number'], c['street name'], c['city'],',', c['state'],',', c['zip code'])
|
||||||
33
python/atms-310/homework/homework1.txt
Executable file
33
python/atms-310/homework/homework1.txt
Executable file
@ -0,0 +1,33 @@
|
|||||||
|
1. input:
|
||||||
|
keyboard, mouse, other HID's, cameras, joysticks, game controllers
|
||||||
|
output:
|
||||||
|
any kind of display, headphones, speakers, vibration motors, a teletype terminal
|
||||||
|
|
||||||
|
2. outputs of operations as stated:
|
||||||
|
True
|
||||||
|
33.0
|
||||||
|
24
|
||||||
|
False
|
||||||
|
True
|
||||||
|
False
|
||||||
|
operations of opposite result for a,d,e,f:
|
||||||
|
3.0 == 3.1
|
||||||
|
4 == 4
|
||||||
|
(6 <= 5) or (5 <= 4)
|
||||||
|
(3 <= 5) and (3 <= 4)
|
||||||
|
|
||||||
|
3. address dict
|
||||||
|
|
||||||
|
redmond costco (no i dont live in redmond)
|
||||||
|
c = {'building number': '7725',
|
||||||
|
'street name': '188th Ave NE',
|
||||||
|
'city': 'Redmond',
|
||||||
|
'state': 'Washington',
|
||||||
|
'zip code' : 98052}
|
||||||
|
|
||||||
|
print('redmond costco is located at:')
|
||||||
|
print(c['building number'], c['street name'], c['city'],',', c['state'],',', c['zip code'])
|
||||||
|
|
||||||
|
# the above code outputs this:
|
||||||
|
redmond costco is located at:
|
||||||
|
7725 188th Ave NE Redmond , Washington , 98052
|
||||||
13
python/atms-310/homework/homework2.py
Executable file
13
python/atms-310/homework/homework2.py
Executable file
@ -0,0 +1,13 @@
|
|||||||
|
import numpy
|
||||||
|
rainfall = [0.0, 0.1, 0.6, 0.7, 0.4, 0.3]
|
||||||
|
|
||||||
|
for n in range(len(rainfall)):
|
||||||
|
x = rainfall[n]*25.4
|
||||||
|
if x < 0:
|
||||||
|
raise ValueError(
|
||||||
|
'make sure no one is drinking out of the rainfall meter')
|
||||||
|
elif x >= 10:
|
||||||
|
print(x)
|
||||||
|
|
||||||
|
z = numpy.max(rainfall)
|
||||||
|
print(z*25.4)
|
||||||
344
python/atms-310/homework/hw3/color.txt
Executable file
344
python/atms-310/homework/hw3/color.txt
Executable file
@ -0,0 +1,344 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||||
|
<plist version="1.0">
|
||||||
|
<dict>
|
||||||
|
<key>Ansi 0 Color</key>
|
||||||
|
<dict>
|
||||||
|
<key>Alpha Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Blue Component</key>
|
||||||
|
<real>0.0</real>
|
||||||
|
<key>Color Space</key>
|
||||||
|
<string>sRGB</string>
|
||||||
|
<key>Green Component</key>
|
||||||
|
<real>0.0</real>
|
||||||
|
<key>Red Component</key>
|
||||||
|
<real>0.0</real>
|
||||||
|
</dict>
|
||||||
|
<key>Ansi 1 Color</key>
|
||||||
|
<dict>
|
||||||
|
<key>Alpha Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Blue Component</key>
|
||||||
|
<real>0.0</real>
|
||||||
|
<key>Color Space</key>
|
||||||
|
<string>sRGB</string>
|
||||||
|
<key>Green Component</key>
|
||||||
|
<real>0.0</real>
|
||||||
|
<key>Red Component</key>
|
||||||
|
<real>0.66666668653488159</real>
|
||||||
|
</dict>
|
||||||
|
<key>Ansi 10 Color</key>
|
||||||
|
<dict>
|
||||||
|
<key>Alpha Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Blue Component</key>
|
||||||
|
<real>0.3333333432674408</real>
|
||||||
|
<key>Color Space</key>
|
||||||
|
<string>sRGB</string>
|
||||||
|
<key>Green Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Red Component</key>
|
||||||
|
<real>0.3333333432674408</real>
|
||||||
|
</dict>
|
||||||
|
<key>Ansi 11 Color</key>
|
||||||
|
<dict>
|
||||||
|
<key>Alpha Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Blue Component</key>
|
||||||
|
<real>0.3333333432674408</real>
|
||||||
|
<key>Color Space</key>
|
||||||
|
<string>sRGB</string>
|
||||||
|
<key>Green Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Red Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
</dict>
|
||||||
|
<key>Ansi 12 Color</key>
|
||||||
|
<dict>
|
||||||
|
<key>Alpha Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Blue Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Color Space</key>
|
||||||
|
<string>sRGB</string>
|
||||||
|
<key>Green Component</key>
|
||||||
|
<real>0.3333333432674408</real>
|
||||||
|
<key>Red Component</key>
|
||||||
|
<real>0.3333333432674408</real>
|
||||||
|
</dict>
|
||||||
|
<key>Ansi 13 Color</key>
|
||||||
|
<dict>
|
||||||
|
<key>Alpha Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Blue Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Color Space</key>
|
||||||
|
<string>sRGB</string>
|
||||||
|
<key>Green Component</key>
|
||||||
|
<real>0.3333333432674408</real>
|
||||||
|
<key>Red Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
</dict>
|
||||||
|
<key>Ansi 14 Color</key>
|
||||||
|
<dict>
|
||||||
|
<key>Alpha Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Blue Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Color Space</key>
|
||||||
|
<string>sRGB</string>
|
||||||
|
<key>Green Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Red Component</key>
|
||||||
|
<real>0.3333333432674408</real>
|
||||||
|
</dict>
|
||||||
|
<key>Ansi 15 Color</key>
|
||||||
|
<dict>
|
||||||
|
<key>Alpha Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Blue Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Color Space</key>
|
||||||
|
<string>sRGB</string>
|
||||||
|
<key>Green Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Red Component</key>
|
||||||
|
<real>0.99999600648880005</real>
|
||||||
|
</dict>
|
||||||
|
<key>Ansi 2 Color</key>
|
||||||
|
<dict>
|
||||||
|
<key>Alpha Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Blue Component</key>
|
||||||
|
<real>0.0</real>
|
||||||
|
<key>Color Space</key>
|
||||||
|
<string>sRGB</string>
|
||||||
|
<key>Green Component</key>
|
||||||
|
<real>0.66666668653488159</real>
|
||||||
|
<key>Red Component</key>
|
||||||
|
<real>0.0</real>
|
||||||
|
</dict>
|
||||||
|
<key>Ansi 3 Color</key>
|
||||||
|
<dict>
|
||||||
|
<key>Alpha Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Blue Component</key>
|
||||||
|
<real>0.0</real>
|
||||||
|
<key>Color Space</key>
|
||||||
|
<string>sRGB</string>
|
||||||
|
<key>Green Component</key>
|
||||||
|
<real>0.3333333432674408</real>
|
||||||
|
<key>Red Component</key>
|
||||||
|
<real>0.66666668653488159</real>
|
||||||
|
</dict>
|
||||||
|
<key>Ansi 4 Color</key>
|
||||||
|
<dict>
|
||||||
|
<key>Alpha Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Blue Component</key>
|
||||||
|
<real>0.66666668653488159</real>
|
||||||
|
<key>Color Space</key>
|
||||||
|
<string>sRGB</string>
|
||||||
|
<key>Green Component</key>
|
||||||
|
<real>0.0</real>
|
||||||
|
<key>Red Component</key>
|
||||||
|
<real>0.0</real>
|
||||||
|
</dict>
|
||||||
|
<key>Ansi 5 Color</key>
|
||||||
|
<dict>
|
||||||
|
<key>Alpha Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Blue Component</key>
|
||||||
|
<real>0.66666668653488159</real>
|
||||||
|
<key>Color Space</key>
|
||||||
|
<string>sRGB</string>
|
||||||
|
<key>Green Component</key>
|
||||||
|
<real>0.0</real>
|
||||||
|
<key>Red Component</key>
|
||||||
|
<real>0.66666668653488159</real>
|
||||||
|
</dict>
|
||||||
|
<key>Ansi 6 Color</key>
|
||||||
|
<dict>
|
||||||
|
<key>Alpha Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Blue Component</key>
|
||||||
|
<real>0.66666668653488159</real>
|
||||||
|
<key>Color Space</key>
|
||||||
|
<string>sRGB</string>
|
||||||
|
<key>Green Component</key>
|
||||||
|
<real>0.66666668653488159</real>
|
||||||
|
<key>Red Component</key>
|
||||||
|
<real>0.0</real>
|
||||||
|
</dict>
|
||||||
|
<key>Ansi 7 Color</key>
|
||||||
|
<dict>
|
||||||
|
<key>Alpha Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Blue Component</key>
|
||||||
|
<real>0.66666668653488159</real>
|
||||||
|
<key>Color Space</key>
|
||||||
|
<string>sRGB</string>
|
||||||
|
<key>Green Component</key>
|
||||||
|
<real>0.66666668653488159</real>
|
||||||
|
<key>Red Component</key>
|
||||||
|
<real>0.66666668653488159</real>
|
||||||
|
</dict>
|
||||||
|
<key>Ansi 8 Color</key>
|
||||||
|
<dict>
|
||||||
|
<key>Alpha Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Blue Component</key>
|
||||||
|
<real>0.3333333432674408</real>
|
||||||
|
<key>Color Space</key>
|
||||||
|
<string>sRGB</string>
|
||||||
|
<key>Green Component</key>
|
||||||
|
<real>0.3333333432674408</real>
|
||||||
|
<key>Red Component</key>
|
||||||
|
<real>0.3333333432674408</real>
|
||||||
|
</dict>
|
||||||
|
<key>Ansi 9 Color</key>
|
||||||
|
<dict>
|
||||||
|
<key>Alpha Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Blue Component</key>
|
||||||
|
<real>0.3333333432674408</real>
|
||||||
|
<key>Color Space</key>
|
||||||
|
<string>sRGB</string>
|
||||||
|
<key>Green Component</key>
|
||||||
|
<real>0.3333333432674408</real>
|
||||||
|
<key>Red Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
</dict>
|
||||||
|
<key>Background Color</key>
|
||||||
|
<dict>
|
||||||
|
<key>Alpha Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Blue Component</key>
|
||||||
|
<real>0.0</real>
|
||||||
|
<key>Color Space</key>
|
||||||
|
<string>sRGB</string>
|
||||||
|
<key>Green Component</key>
|
||||||
|
<real>0.0</real>
|
||||||
|
<key>Red Component</key>
|
||||||
|
<real>0.0</real>
|
||||||
|
</dict>
|
||||||
|
<key>Badge Color</key>
|
||||||
|
<dict>
|
||||||
|
<key>Alpha Component</key>
|
||||||
|
<real>0.5</real>
|
||||||
|
<key>Blue Component</key>
|
||||||
|
<real>0.0</real>
|
||||||
|
<key>Color Space</key>
|
||||||
|
<string>sRGB</string>
|
||||||
|
<key>Green Component</key>
|
||||||
|
<real>0.1491314172744751</real>
|
||||||
|
<key>Red Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
</dict>
|
||||||
|
<key>Bold Color</key>
|
||||||
|
<dict>
|
||||||
|
<key>Alpha Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Blue Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Color Space</key>
|
||||||
|
<string>sRGB</string>
|
||||||
|
<key>Green Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Red Component</key>
|
||||||
|
<real>0.99999600648880005</real>
|
||||||
|
</dict>
|
||||||
|
<key>Cursor Color</key>
|
||||||
|
<dict>
|
||||||
|
<key>Alpha Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Blue Component</key>
|
||||||
|
<real>0.72337132692337036</real>
|
||||||
|
<key>Color Space</key>
|
||||||
|
<string>sRGB</string>
|
||||||
|
<key>Green Component</key>
|
||||||
|
<real>0.72338062524795532</real>
|
||||||
|
<key>Red Component</key>
|
||||||
|
<real>0.72336345911026001</real>
|
||||||
|
</dict>
|
||||||
|
<key>Cursor Guide Color</key>
|
||||||
|
<dict>
|
||||||
|
<key>Alpha Component</key>
|
||||||
|
<real>0.25</real>
|
||||||
|
<key>Blue Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Color Space</key>
|
||||||
|
<string>sRGB</string>
|
||||||
|
<key>Green Component</key>
|
||||||
|
<real>0.9268307089805603</real>
|
||||||
|
<key>Red Component</key>
|
||||||
|
<real>0.70213186740875244</real>
|
||||||
|
</dict>
|
||||||
|
<key>Cursor Text Color</key>
|
||||||
|
<dict>
|
||||||
|
<key>Alpha Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Blue Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Color Space</key>
|
||||||
|
<string>sRGB</string>
|
||||||
|
<key>Green Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Red Component</key>
|
||||||
|
<real>0.99999600648880005</real>
|
||||||
|
</dict>
|
||||||
|
<key>Foreground Color</key>
|
||||||
|
<dict>
|
||||||
|
<key>Alpha Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Blue Component</key>
|
||||||
|
<real>0.66666668653488159</real>
|
||||||
|
<key>Color Space</key>
|
||||||
|
<string>sRGB</string>
|
||||||
|
<key>Green Component</key>
|
||||||
|
<real>0.66666668653488159</real>
|
||||||
|
<key>Red Component</key>
|
||||||
|
<real>0.66666668653488159</real>
|
||||||
|
</dict>
|
||||||
|
<key>Link Color</key>
|
||||||
|
<dict>
|
||||||
|
<key>Alpha Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Blue Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Color Space</key>
|
||||||
|
<string>sRGB</string>
|
||||||
|
<key>Green Component</key>
|
||||||
|
<real>0.3333333432674408</real>
|
||||||
|
<key>Red Component</key>
|
||||||
|
<real>0.3333333432674408</real>
|
||||||
|
</dict>
|
||||||
|
<key>Selected Text Color</key>
|
||||||
|
<dict>
|
||||||
|
<key>Alpha Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Blue Component</key>
|
||||||
|
<real>0.0</real>
|
||||||
|
<key>Color Space</key>
|
||||||
|
<string>sRGB</string>
|
||||||
|
<key>Green Component</key>
|
||||||
|
<real>0.0</real>
|
||||||
|
<key>Red Component</key>
|
||||||
|
<real>0.0</real>
|
||||||
|
</dict>
|
||||||
|
<key>Selection Color</key>
|
||||||
|
<dict>
|
||||||
|
<key>Alpha Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Blue Component</key>
|
||||||
|
<real>1</real>
|
||||||
|
<key>Color Space</key>
|
||||||
|
<string>sRGB</string>
|
||||||
|
<key>Green Component</key>
|
||||||
|
<real>0.86970102787017822</real>
|
||||||
|
<key>Red Component</key>
|
||||||
|
<real>0.75813239812850952</real>
|
||||||
|
</dict>
|
||||||
|
</dict>
|
||||||
|
</plist>
|
||||||
54
python/atms-310/homework/hw3/homework3.py
Executable file
54
python/atms-310/homework/hw3/homework3.py
Executable file
@ -0,0 +1,54 @@
|
|||||||
|
import numpy as np
|
||||||
|
import scipy.stats as s
|
||||||
|
import glob as glob # glob
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
filelist = glob.glob("hw3_*.txt")
|
||||||
|
filelist.sort()
|
||||||
|
|
||||||
|
def read(file):
|
||||||
|
fileobj = open(file, "r")
|
||||||
|
outputstr = fileobj.readlines()
|
||||||
|
fileobj.close()
|
||||||
|
outputarray = np.zeros(len(outputstr))
|
||||||
|
for i in np.arange(len(outputstr)):
|
||||||
|
outputarray[i] = float(outputstr[i])
|
||||||
|
return outputarray
|
||||||
|
|
||||||
|
parameters = ["mean", "median", "std", "iqr", "skew", "kurtosis"]
|
||||||
|
|
||||||
|
for i in range(len(filelist)):
|
||||||
|
print(filelist[i])
|
||||||
|
data = np.array(read(filelist[i]))
|
||||||
|
for n in range (len(parameters)):
|
||||||
|
operation = parameters[n]
|
||||||
|
print(str(operation) + " " + np.operation(data))
|
||||||
|
|
||||||
|
|
||||||
|
#for n in range(len(filelist)):
|
||||||
|
# print(filelist[n])
|
||||||
|
# mean = np.mean(read(filelist[n]))
|
||||||
|
# print("mean: " + str(mean))
|
||||||
|
# median = np.median(read(filelist[n]))
|
||||||
|
# print("median: " + str(median))
|
||||||
|
# stddev = np.std(read(filelist[n]))
|
||||||
|
# print("stddev: " + str(stddev))
|
||||||
|
# iqr = s.iqr(read(filelist[n]))
|
||||||
|
# print("iqr: " + str(iqr))
|
||||||
|
# skew = s.skew(read(filelist[n]))
|
||||||
|
# print("skew: " + str(skew))
|
||||||
|
# kurtosis = s.kurtosis(read(filelist[n]))
|
||||||
|
# print("kurtosis: " + str(kurtosis)+"\n")
|
||||||
|
|
||||||
|
# the mean and median are similar for all files, indicating solid, outlier free data.
|
||||||
|
# standard deviation is quite high for everything except wind shear, indicating either \
|
||||||
|
# inconsistent readings for everything but wind shear, or more likely, smaller units and \
|
||||||
|
# higher rates of change.
|
||||||
|
# the difference between shr1's iqr and stddev is larger than that of shr2's (shr2's is \
|
||||||
|
# quite close to its stddev), possibility of one minor outlier
|
||||||
|
# none of the data is very skewed, the largest (absolute value) being 0.54896, and \
|
||||||
|
# all of the data has negative kurtosis, meaning when distibuted, it will have a shallower \
|
||||||
|
# peak than the bell curve (e^x^2)
|
||||||
|
# the february and may datasets are similar in that their wind shears are similar, though \
|
||||||
|
# mays is still larger. they are different in that mays SRH and CAPE are both much higher, \
|
||||||
|
# so mays tornadoes are much stronger.
|
||||||
17
python/atms-310/homework/hw3/hw3.py
Executable file
17
python/atms-310/homework/hw3/hw3.py
Executable file
@ -0,0 +1,17 @@
|
|||||||
|
import numpy as np
|
||||||
|
import scipy.stats as s
|
||||||
|
import glob as glob
|
||||||
|
|
||||||
|
calc = {"mean":np.std, "median":np.median, "std":np.std, "iqr":s.iqr,\
|
||||||
|
"skew":s.skew, "kurtosis":s.kurtosis}
|
||||||
|
|
||||||
|
print(calc["kurtosis"])
|
||||||
|
def read(file):
|
||||||
|
fileobj = open(file, "r")
|
||||||
|
outputstr = fileobj.readlines()
|
||||||
|
fileobj.close()
|
||||||
|
outputarray = np.zeros(len(outputstr))
|
||||||
|
for i in np.arange(len(outputstr)):
|
||||||
|
outputarray[i] = float(outputstr[i])
|
||||||
|
return outputarray
|
||||||
|
|
||||||
9
python/atms-310/homework/hw3/hw3_01srh1.txt
Executable file
9
python/atms-310/homework/hw3/hw3_01srh1.txt
Executable file
@ -0,0 +1,9 @@
|
|||||||
|
2.5
|
||||||
|
140.01
|
||||||
|
127.19
|
||||||
|
116.8
|
||||||
|
211.31
|
||||||
|
115.35
|
||||||
|
220.38
|
||||||
|
250.54
|
||||||
|
248.61
|
||||||
10
python/atms-310/homework/hw3/hw3_01srh2.txt
Executable file
10
python/atms-310/homework/hw3/hw3_01srh2.txt
Executable file
@ -0,0 +1,10 @@
|
|||||||
|
383.79
|
||||||
|
364.37
|
||||||
|
364.37
|
||||||
|
517.94
|
||||||
|
517.94
|
||||||
|
630.18
|
||||||
|
240.08
|
||||||
|
203.42
|
||||||
|
184.33
|
||||||
|
211.19
|
||||||
9
python/atms-310/homework/hw3/hw3_06shr1.txt
Executable file
9
python/atms-310/homework/hw3/hw3_06shr1.txt
Executable file
@ -0,0 +1,9 @@
|
|||||||
|
67.4134
|
||||||
|
63.5197
|
||||||
|
61.7
|
||||||
|
55.6912
|
||||||
|
56.6491
|
||||||
|
48.4201
|
||||||
|
46.6137
|
||||||
|
41.388
|
||||||
|
43.7989
|
||||||
10
python/atms-310/homework/hw3/hw3_06shr2.txt
Executable file
10
python/atms-310/homework/hw3/hw3_06shr2.txt
Executable file
@ -0,0 +1,10 @@
|
|||||||
|
62.3392
|
||||||
|
60.4778
|
||||||
|
60.4778
|
||||||
|
68.9632
|
||||||
|
68.9632
|
||||||
|
72.1033
|
||||||
|
63.5346
|
||||||
|
63.4428
|
||||||
|
63.272
|
||||||
|
52.7143
|
||||||
9
python/atms-310/homework/hw3/hw3_mlcape1.txt
Executable file
9
python/atms-310/homework/hw3/hw3_mlcape1.txt
Executable file
@ -0,0 +1,9 @@
|
|||||||
|
205.47
|
||||||
|
656.44
|
||||||
|
691.44
|
||||||
|
446.69
|
||||||
|
448.34
|
||||||
|
1069.41
|
||||||
|
808.91
|
||||||
|
983
|
||||||
|
307.58
|
||||||
10
python/atms-310/homework/hw3/hw3_mlcape2.txt
Executable file
10
python/atms-310/homework/hw3/hw3_mlcape2.txt
Executable file
@ -0,0 +1,10 @@
|
|||||||
|
3167.88
|
||||||
|
2844.88
|
||||||
|
2844.88
|
||||||
|
2146.88
|
||||||
|
2146.88
|
||||||
|
1820.75
|
||||||
|
741.62
|
||||||
|
1042.75
|
||||||
|
810.12
|
||||||
|
1314.88
|
||||||
BIN
python/atms-310/midterms/MT 1.pdf
Executable file
BIN
python/atms-310/midterms/MT 1.pdf
Executable file
Binary file not shown.
58
python/atms-310/midterms/midterm1.py
Executable file
58
python/atms-310/midterms/midterm1.py
Executable file
@ -0,0 +1,58 @@
|
|||||||
|
## 1
|
||||||
|
a = 1
|
||||||
|
b = 2
|
||||||
|
c = -3
|
||||||
|
|
||||||
|
# a
|
||||||
|
# ((a<b) or (a>=c)) and (a==1)
|
||||||
|
# a is less than b, and a is greater than or equal to 3, so the or is true. a also equals 1, so the and is true. overall, this statement is true.
|
||||||
|
|
||||||
|
# b
|
||||||
|
# ((a != b) and (a <= c)) or (a <= c)
|
||||||
|
# a does not equal b, but a is not less than or equal to c, so the and is false.
|
||||||
|
# a is still not less than or equal to c, so the or is also false, making the statement as a whole false.
|
||||||
|
|
||||||
|
# c
|
||||||
|
# ((a == c) or (b > c)) and (-a*b < c)
|
||||||
|
# a does not equal c, but b is greater than c, so the or is true. -a*b=-2 which is greater than c, so the and is false, making the whole statement false.
|
||||||
|
|
||||||
|
# d
|
||||||
|
# (a <= 1) and ((b != c*a) or (b == a*b))
|
||||||
|
# a is less than or equal to 1. b does not equal c*a, but b does equal a*b, overall true
|
||||||
|
|
||||||
|
## 2
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
data = np.zeros((4,3))
|
||||||
|
data = np.array([[7.6, 288.3, 278.4], [6.3, 278.6, 271.3], [5.2, 272.1, 265.3],[3.7, 250.3, 230.4]])
|
||||||
|
|
||||||
|
def atmo(x):
|
||||||
|
hpa = x[0:5,0]*133.322
|
||||||
|
dew = np.zeros((4))
|
||||||
|
dewdep = x[0:5,1]-x[0:5,2]
|
||||||
|
for i in range(len(dewdep)):
|
||||||
|
z = dewdep[i]
|
||||||
|
if z < 0:
|
||||||
|
raise ValueError('dewpoint depression negative, check temp and dewpoint values')
|
||||||
|
return hpa,dewdep
|
||||||
|
|
||||||
|
|
||||||
|
print(np.array(atmo(data)))
|
||||||
|
|
||||||
|
# row 0 is pascals conversion, row 1 is dewpoint depression
|
||||||
|
# note: the given conversion factor seems to be from mmHg to pascals, instead of hectopascals. maybe im wrong.
|
||||||
|
|
||||||
|
# 2(g)
|
||||||
|
# in order to account for 10 rows instead of 4, the only change needed would be to initialize an array 10 deep, and then actually populate it with the extra data.
|
||||||
|
# all operations within my function "atmo" are only dependent on start locations, so making the end of the array further away wouldnt matter.
|
||||||
|
# as for the for loop looking for negative dewdeps, that is iterative (slow i know) but can (and will) adapt to the length (depth) of the resulting array of dewdep values.
|
||||||
|
# ok no theres one more thing, I would also need to initialize a deeper array (10 instead of 4, this is inside of "atmo") for the dewdep values to be inserted into. theres probably a way to do this that gets the amount of rows in the actual data array, but i dont know how to do it yet.
|
||||||
|
|
||||||
|
# 2(h)
|
||||||
|
# the only real problem that could plague the data is it either being zero or negative, and one way of verifying the datas integrity would be to iterate through all of it in a for loop before (next line)
|
||||||
|
# doing any calculations with it, looking for values less than or equal to 0.
|
||||||
|
|
||||||
|
# BONUS
|
||||||
|
# I didnt actually study,(mb bro) I just reviewed the nonsensical syntax of numpy.zeros and how it needs two sets of parentheses. unthinkable.
|
||||||
|
# I use a 3440x1440 (21:9) monitor, sorry if alot of the text goes off screen
|
||||||
63
python/atms-310/midterms/midterm2.py
Executable file
63
python/atms-310/midterms/midterm2.py
Executable file
@ -0,0 +1,63 @@
|
|||||||
|
import pandas as pd
|
||||||
|
import numpy as np
|
||||||
|
import scipy.stats as s
|
||||||
|
|
||||||
|
# 1a.
|
||||||
|
fileobj = open("./mt2_datafile.txt", "r")
|
||||||
|
|
||||||
|
# 1b.
|
||||||
|
datai = fileobj.readlines()
|
||||||
|
datam = datai[0]
|
||||||
|
dataf = datam.split(',')
|
||||||
|
print(dataf)
|
||||||
|
|
||||||
|
# 1c.
|
||||||
|
dataa = np.array(dataf)
|
||||||
|
dataa = np.reshape(dataf,(3,7))
|
||||||
|
print(dataa)
|
||||||
|
|
||||||
|
# 1d.
|
||||||
|
for n in range(len(dataf)):
|
||||||
|
dataf[n] = int(dataf[n])
|
||||||
|
print(dataf)
|
||||||
|
|
||||||
|
print(np.mean(dataf))
|
||||||
|
print(np.median(dataf))
|
||||||
|
print(np.std(dataf))
|
||||||
|
print(s.iqr(dataf))
|
||||||
|
|
||||||
|
# mean and median are close, no outliers
|
||||||
|
# stddev is quite small, suggesting consistent data
|
||||||
|
# iqr is larger than stddev, so the middle is more spread out than the rest (??? perhaps ???)
|
||||||
|
|
||||||
|
# 2a.
|
||||||
|
students = {"name": ["garrus vakarian", "matilda bradbury", "cordelia vorkosigan", "kira nerys", "Jean-Luc Picard"],\
|
||||||
|
"credits": [37,43,36,23,50], "GPA": [3.2,4.0,3.7,3.6,3.4], "Hometown": ["Palaven", "Whitestone","Vashnoi",\
|
||||||
|
"Dahkur", "La Barre"]}
|
||||||
|
|
||||||
|
# 2b.
|
||||||
|
# fyi: sdt stands for "superior data type"
|
||||||
|
sdt = pd.DataFrame(students)
|
||||||
|
print(sdt)
|
||||||
|
# beautiful. incredible. just amazing.
|
||||||
|
|
||||||
|
# 2c.
|
||||||
|
sdt.set_index("name",inplace=True)
|
||||||
|
|
||||||
|
# 2d.
|
||||||
|
print("kira's GPA:" + str(sdt.loc["kira nerys","GPA"]))
|
||||||
|
|
||||||
|
# 2e.
|
||||||
|
sdt.loc["matilda bradbury","credits"] = 44
|
||||||
|
print(sdt)
|
||||||
|
|
||||||
|
# 2f.
|
||||||
|
print(sdt.credits.describe())
|
||||||
|
print(sdt.GPA.describe())
|
||||||
|
|
||||||
|
# 2g.
|
||||||
|
|
||||||
|
height = [10,23,-1,43,100]
|
||||||
|
|
||||||
|
sdt["height (in meters)"] = height
|
||||||
|
print(sdt)
|
||||||
1
python/atms-310/midterms/mt2_datafile.txt
Executable file
1
python/atms-310/midterms/mt2_datafile.txt
Executable file
@ -0,0 +1 @@
|
|||||||
|
1,4,7,3,7,8,3,2,7,4,8,7,3,9,5,8,3,7,3,8,5
|
||||||
BIN
python/atms-310/notebooks/.DS_Store
vendored
Executable file
BIN
python/atms-310/notebooks/.DS_Store
vendored
Executable file
Binary file not shown.
229
python/atms-310/notebooks/MT1 Review.ipynb
Executable file
229
python/atms-310/notebooks/MT1 Review.ipynb
Executable file
@ -0,0 +1,229 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"id": "1bf363de-ca7c-44a6-bd2f-4ca809666863",
|
||||||
|
"metadata": {
|
||||||
|
"tags": []
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"<h1>MIDTERM 1 REVIEW</h1>\n",
|
||||||
|
"\n",
|
||||||
|
"<h2>10/16/2023</h2>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"id": "51a1ad77-a7f8-4438-a7da-f082e340f798",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h3><b>Lecture Name:</b> Introduction to Python and Computer Architecture</h3>\n",
|
||||||
|
" \n",
|
||||||
|
"<h3><b>File Name:</b> Week 01 W.pdf</h3>\n",
|
||||||
|
" \n",
|
||||||
|
"<h3><b>Class Date:</b> 09/27/2023</h3>\n",
|
||||||
|
"\n",
|
||||||
|
"<b>Key Points:</b>\n",
|
||||||
|
"\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li>Programming is the act of writing an <b>algorithm</b> using a specific syntax to solve a problem.\n",
|
||||||
|
" <ul>\n",
|
||||||
|
" <li>A big part of programming is taking a problem apart into smaller pieces that can be understood by a computer\n",
|
||||||
|
" </ul>\n",
|
||||||
|
" <li>A computer's structure consists of:\n",
|
||||||
|
" <ul>\n",
|
||||||
|
" <li>Input and output devices\n",
|
||||||
|
" <li>A central processing unit composed of a control unit and an arithmetic/logic unit\n",
|
||||||
|
" <li>A memory unit"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"id": "e30ff5c5-2236-400b-9157-73a77cae261c",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h3><b>Lecture Name:</b> Print, Calculator, Variable Types and Operators</h3>\n",
|
||||||
|
" \n",
|
||||||
|
"<h3><b>File Name:</b> Week 01 F.ipynb</h3>\n",
|
||||||
|
" \n",
|
||||||
|
"<h3><b>Class Date:</b> 09/29/2023</h3>\n",
|
||||||
|
"\n",
|
||||||
|
"<b>Key Points:</b>\n",
|
||||||
|
"\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li>An <b>integer</b> variable is a number with no decimal point\n",
|
||||||
|
" <li>A <b>floating point</b> variable is a number with a decimal point\n",
|
||||||
|
" <li>A <b>string</b> variable is text\n",
|
||||||
|
" <li>A <b>Boolean</b> variable can take on the values <b>True</b> and <b>False</b>\n",
|
||||||
|
" <li>A <b>NoneType</b>variable can take on the value <b>None</b>\n",
|
||||||
|
" <li>Python uses dynamic typing, which means you don't need to define a variable's type when you first use that variable\n",
|
||||||
|
" <li>The type() command lets you see what type a given variable is. int(), float(), and str() can be used to convert to different variable types\n",
|
||||||
|
" <li>Combining a float and an integer results in a float\n",
|
||||||
|
" <li>Combining a string and an integer or float results in a TypeError\n",
|
||||||
|
" <li>Floats are often prone to rounding errors\n",
|
||||||
|
" <li><b>and</b> and <b>or</b> can be used to combine Boolean variables"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"id": "c8dcb344-0708-4ba9-9ccb-df22e34edea2",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h3><b>Lecture Name:</b> Lists and Dictionaries</h3>\n",
|
||||||
|
" \n",
|
||||||
|
"<h3><b>File Name:</b> Week 02 M.ipynb</h3>\n",
|
||||||
|
" \n",
|
||||||
|
"<h3><b>Class Date:</b> 10/02/2023</h3>\n",
|
||||||
|
"\n",
|
||||||
|
"<b>Key Points:</b>\n",
|
||||||
|
"\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li> A list is a <b>mutable</b>, <b>ordered</b> sequence of elements\n",
|
||||||
|
" <li> Python counts starting with 0, not 1\n",
|
||||||
|
" <li> You can also count backwards from the end of a list using negative numbers\n",
|
||||||
|
" <li> A list can be sliced, where the slice is defined by a range that has an inclusive lower bound and an exclusive upper bound\n",
|
||||||
|
" <li> Values in a list can be changed by assignment or by particular methods\n",
|
||||||
|
" <li> A tuple is an <b>immutable</b>, <b>ordered</b> sequence of elements\n",
|
||||||
|
" <li> A dictionary is a <b>mutable</b>, <b>unordered</b> sequence of elements consisting of key:value pairs"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"id": "0af5f1b7-48e9-4131-a331-5e35826a677a",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h3><b>Lecture Name:</b> Functions and Logic</h3>\n",
|
||||||
|
" \n",
|
||||||
|
"<h3><b>File Name:</b> Week 02 W.ipynb</h3>\n",
|
||||||
|
" \n",
|
||||||
|
"<h3><b>Class Date:</b> 10/04/2023</h3>\n",
|
||||||
|
"\n",
|
||||||
|
"<b>Key Points:</b>\n",
|
||||||
|
"\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li> A <b>function</b> is a block of code that can be called\n",
|
||||||
|
" <li> Functions can be called using either positional or keyword arguments\n",
|
||||||
|
" <li> Positional arguments can be described via lists and keyword arguments can be desribed via dictionaries\n",
|
||||||
|
" <li> Python uses if statements for logical constructs\n",
|
||||||
|
" <li> The code within an <b>if</b> statement is run if the current statement is true\n",
|
||||||
|
" <li> The code within an <b>elif</b> statement applies if prior statements are not true <b>and</b> the current statement is true\n",
|
||||||
|
" <li> The code within an <b>else</b> statement applies if all prior statements are not true"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"id": "44c499c2-bab1-48be-8edc-c6c59a23659f",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h3><b>Lecture Name:</b> Loops</h3>\n",
|
||||||
|
" \n",
|
||||||
|
"<h3><b>File Name:</b> Week 02 F.ipynb</h3>\n",
|
||||||
|
" \n",
|
||||||
|
"<h3><b>Class Date:</b> 10/06/2023</h3>\n",
|
||||||
|
"\n",
|
||||||
|
"<b>Key Points:</b>\n",
|
||||||
|
"\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li> A <b>for loop</b> lets you repeat an operation a specified number of times\n",
|
||||||
|
" <li> Indentation is critical for lists in Python\n",
|
||||||
|
" <li> The range() function will create a list of all values up to (but not including) the specified integer\n",
|
||||||
|
" <li> Hardcoding is the act of restricting a piece of code so it only works under specific circumstances (generally want to avoid this)\n",
|
||||||
|
" <li>A <b>while loop</b> lets you repeat an operation until a particular condition is met\n",
|
||||||
|
" <li>The index in a while loop must be initialized and care should be taken to avoid infinite loops"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"id": "7a2a73cf-6155-42d8-b792-7144f1821844",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h3><b>Lecture Name:</b> Modules and Exception Handling</h3>\n",
|
||||||
|
" \n",
|
||||||
|
"<h3><b>File Name:</b> Week 03 M.ipynb</h3>\n",
|
||||||
|
" \n",
|
||||||
|
"<h3><b>Class Date:</b> 10/09/2023</h3>\n",
|
||||||
|
"\n",
|
||||||
|
"<b>Key Points:</b>\n",
|
||||||
|
"\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li>A <b>module</b> is a library of Python source code that gives access to new variables and functions\n",
|
||||||
|
" <li>Modules can be imported as whatever name you like\n",
|
||||||
|
" <li>A <b>raise</b> statement lets you define your own error conditions and stop code when they're met\n",
|
||||||
|
" <li>A <b>try/except</b> block will let you fix common issues that would otherwise result in exceptions"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"id": "1972b16e-0c87-482b-8e05-dd4c99b3c11c",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h3><b>Lecture Name:</b> Arrays</h3>\n",
|
||||||
|
" \n",
|
||||||
|
"<h3><b>File Name:</b> Week 02 W.ipynb</h3>\n",
|
||||||
|
" \n",
|
||||||
|
"<h3><b>Class Date:</b> 10/11/2023</h3>\n",
|
||||||
|
"\n",
|
||||||
|
"<b>Key Points:</b>\n",
|
||||||
|
"\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li> An array is NumPy's version of a list, which allows you to work with matrices\n",
|
||||||
|
" <li> All elements of an array are of the same type\n",
|
||||||
|
" <li> You can either create a new array or convert an existing list into one\n",
|
||||||
|
" <li> The zeros() function is useful for initializing an array when you know the shape and size but not the contents\n",
|
||||||
|
" <li> The arange() function serves a similar purpose to the range() function with lists\n",
|
||||||
|
" <li> Similar to lists, arrays can be sliced, but arrays can also be sliced across each of their dimensions"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"id": "31e2ef42-a0ec-468a-8c53-189b314186ee",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h3><b>Lecture Name:</b> Testing Inside Arrays</h3>\n",
|
||||||
|
" \n",
|
||||||
|
"<h3><b>File Name:</b> Week 03 F.ipynb</h3>\n",
|
||||||
|
" \n",
|
||||||
|
"<h3><b>Class Date:</b> 10/13/2023</h3>\n",
|
||||||
|
"\n",
|
||||||
|
"<b>Key Points:</b>\n",
|
||||||
|
"\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li> You can use functions within NumPy to find the shape, number of dimensions, and number of elements in any array\n",
|
||||||
|
" <li> <b>numpy.where()</b> will let you find the locations of elements within an array that meet a specified criterion\n",
|
||||||
|
" <li> Some functions within NumPy allow you to manipulate arrays, such as reshaping, transpoing, unraveling, concatenation, and repeating individual array elements\n",
|
||||||
|
" <li> When you're in a situation with multiple nested loops, often you can instead perform all operations a lot more easily by using array syntax\n",
|
||||||
|
" <li> Mathematical operations act on arrays elementwise\n",
|
||||||
|
" <li> When testing within an array, <b>and</b> and <b>or</b> cannot be used; instead, use NumPy's built-in functions"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"id": "4d9362ec-b4ad-421d-8e13-74527bc19ede",
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3 (ipykernel)",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python3"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 3
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython3",
|
||||||
|
"version": "3.11.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 5
|
||||||
|
}
|
||||||
445
python/atms-310/notebooks/Week 01 F.ipynb
Executable file
445
python/atms-310/notebooks/Week 01 F.ipynb
Executable file
@ -0,0 +1,445 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h1>1. Print, Calculator, Variable Types, and Operators</h1>\n",
|
||||||
|
"<h2>09/29/23</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"<h2>1.0 Introduction to Jupyter Notebooks</h2>\n",
|
||||||
|
"First, this is a Jupyter Notebook, which enables a combination of markdown cells (like this one) to provide description alongside actual code that can be run. If you want to change a markdown cell, simply double-click on the text, make any changes you want to make, and click \"Run\" (the little play button) <b>above</b> to execute. You can add HTML-style tags to markdown cells to add details such as formatting and links.\n",
|
||||||
|
"\n",
|
||||||
|
"There are also code cells, which can actually be executed, just like in a normal programming environment. Click on the below code cell and try clicking \"Run\" (or type Shift+Enter). You can also modify the text that's being printed to the screen and try running it again."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"tags": []
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>1.1 Basic Variables</h2>\n",
|
||||||
|
"Python has <b>dynamic typing</b>, which means that variable types are set automatically based on the input. This is handy if you're coming from an environment like Fortran that requires you to specify each and every time what kind of variable you want to create!\n",
|
||||||
|
"\n",
|
||||||
|
"Here are some of the most important variable types (more on these in a bit):\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li>Integer (short and long)</li>\n",
|
||||||
|
" <li>Floating point (float)</li>\n",
|
||||||
|
" <li>Strings</li>\n",
|
||||||
|
" <li>Booleans</li>\n",
|
||||||
|
" <li>NoneType</li>\n",
|
||||||
|
" <li>Lists and tuples</li> (Tuesday's class)\n",
|
||||||
|
" <li>Dictionaries</li> (Tuesday's class)\n",
|
||||||
|
"</ul>\n",
|
||||||
|
"\n",
|
||||||
|
"Arithmetic operators:\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li>+ is addition</li>\n",
|
||||||
|
" <li>- is subtraction</li>\n",
|
||||||
|
" <li>/ is division</li>\n",
|
||||||
|
" <li>* is multiplication</li>\n",
|
||||||
|
" <li>** is exponentiation</li>\n",
|
||||||
|
"</ul>\n",
|
||||||
|
"\n",
|
||||||
|
"Comparison operators:\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li>> is greater than</li>\n",
|
||||||
|
" <li>< is less than</li>\n",
|
||||||
|
" <li>>= is greater than or equal to</li>\n",
|
||||||
|
" <li><= is less than or equal to</li>\n",
|
||||||
|
" <li>!= is not equal to</li>\n",
|
||||||
|
" <li>== is equal to</li>\n",
|
||||||
|
"</ul>\n",
|
||||||
|
"\n",
|
||||||
|
"<b>Important note:</b> Python is case-sensitive! \"A\" is not the same thing as \"a\"."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Code that is preceded with a hashtag will not be read by the computer.\n",
|
||||||
|
"# These comments are intended for human readers of this code!\n",
|
||||||
|
"# Commenting your code is essential to ensure that you and others\n",
|
||||||
|
"# will be able to interpret it down the road!\n",
|
||||||
|
"\n",
|
||||||
|
"# Now, let's try playing with some numbers...\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Note that all of the above are examples of Python's <b>dynamic typing</b>: assigning a variable a floating point value (i.e., including a decimal point) results in that variable being a float, whereas assigning a variable an integer value (i.e., no decimal point) results in that variable being an integer.\n",
|
||||||
|
"\n",
|
||||||
|
"You can also convert from one to the other using the int() and float() commands!"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Convert a from a float to an integer.\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Convert c from an integer to a float.\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Note that the conversion from float to int <b>loses information</b> along the way: Python merely truncates everything after the decimal point.\n",
|
||||||
|
"\n",
|
||||||
|
"On the other hand, the conversion from int to float is <b>essentially lossless</b>: the same information is maintained."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Now let's try some mathematical operators.\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"When applying mathematical operations, Python tries to keep as much information as possible! This means that an integer and a float interacting together will result in a float as an answer. Likewise, division of integers will give you a float by default (this is new in version 3 of Python).\n",
|
||||||
|
"\n",
|
||||||
|
"<b>Why is a*b not exactly -7.56?</b>\n",
|
||||||
|
"\n",
|
||||||
|
"Floats are not exact numbers! There will always be some degree of rounding errors associated with floating point numbers (because we don't have infinite storage to keep an infinite number of digits after the decimal). As a result, it's good practice when comparing floats not to look for equality, but instead to look for \"close enough\" - there are functions to do this that we will see later!\n",
|
||||||
|
"\n",
|
||||||
|
"You can also represent scientific notation in Python!"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Let's represent 6 x 10^23 in Python!\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>1.2 Strings</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"Strings are the text variable type in Python: they're surrounded either by single or double quotes (it generally doesn't matter which, as long as you're consistent at the start and finish)."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"If you want to combine two strings, you can do so easily with the \"+\" command."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# To add a space, simply throw another string in there.\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# How about combining a string and a float?\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"The <b>TypeError</b> you get in the above example explains the problem: a float cannot be combined in this way with a string. But what if we want to make this change? That's where the str() function comes in handy."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Let's try that again!\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Sometimes you want a new line within the same string. This can be accomplished with the \"escape character\", which in Python is a backslash: \\\\. \"\\n\" will start a new line!"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Creating a multi-line string using the newline character.\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"If you don't want to deal with newlines being created automatically, you can create a raw string!"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# This will give you a nonsense result because \\n is being treated as a new line.\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Instead, tell Python you're going to make a raw string by adding the letter 'r'.\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>1.3 Boolean Variables</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"A Boolean variable can only have two values: <b>True</b> and <b>False</b> (and remember, capitalization counts!) These are the results of the logical tests mentioned earlier!"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"You can also combine conditions using <b>and</b> and <b>or</b>.\n",
|
||||||
|
"\n",
|
||||||
|
"<b>and</b>: Both statements must be <b>True</b> in order for the entire statement to be <b>True</b>.\n",
|
||||||
|
"\n",
|
||||||
|
"<b>or</b>: Either statement (or both) can be <b>True</b> in order for the entire statement to be <b>True</b>."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>1.4 NoneType</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"A NoneType variable can only have one value: <b>None</b> (and capitalization counts!). \n",
|
||||||
|
"\n",
|
||||||
|
"Why would we want this? Consider the scenario where you want to make sure there's no value already in a given variable (so, for example, if you're working with thousands of lines of code and the same variable types keep coming up). Setting that variable to None (via something like <b>a = None</b>) means you're guaranteed not to be messing around with any previous values by accident."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h1>TAKE-HOME POINTS</h1>\n",
|
||||||
|
"\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li>Python has a variety of data types, many of which we saw today!</li>\n",
|
||||||
|
" <li>An <b>integer</b> variable is a number with no decimal point.</li>\n",
|
||||||
|
" <li>A <b>floating point</b> variable is a number with a decimal point</li>\n",
|
||||||
|
" <li>A <b>string</b> variable is text.</li>\n",
|
||||||
|
" <li>A <b>Boolean</b> variable can take on the values <b>True</b> and <b>False</b>.</li>\n",
|
||||||
|
" <li>A <b>NoneType</b> variable can take on the value <b>None</b>.</li>\n",
|
||||||
|
" <li>Python uses dynamic typing, which means you don't need to define a variable's type when you first use that variable.</li>\n",
|
||||||
|
" <li>The type() command lets you see what type a given variable is. int(), float(), and str() can be used to convert to different variable types.</li>\n",
|
||||||
|
" <li>Combining a float and an integer results in a float.</li>\n",
|
||||||
|
" <li>Combining a string and an integer or float results in a TypeError.</li>\n",
|
||||||
|
" <li>Floats are often prone to rounding errors.</li>\n",
|
||||||
|
" <li><b>and</b> and <b>or</b> can be used to combine Boolean variables.</li>\n",
|
||||||
|
"</ul>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3 (ipykernel)",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python3"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 3
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython3",
|
||||||
|
"version": "3.10.10"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 4
|
||||||
|
}
|
||||||
301
python/atms-310/notebooks/Week 02 F.ipynb
Executable file
301
python/atms-310/notebooks/Week 02 F.ipynb
Executable file
@ -0,0 +1,301 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h1>4. Loops</h1>\n",
|
||||||
|
"<h2>10/06/23</h2>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>4.0 Last Time...</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li>A <b>function</b> is a block of code that can be called.</li>\n",
|
||||||
|
" <li>Functions can be called using either positional or keyword arguments.</li>\n",
|
||||||
|
" <li>Positional arguments can be described via lists and keyword arguments can be described via dictionaries.</li>\n",
|
||||||
|
" <li>Python uses if statements for logical constructs.</li>\n",
|
||||||
|
" <li>The code within an <b>if</b> statement is run if the current statement is true.</li>\n",
|
||||||
|
" <li>The code within an <b>elif</b> statement applies if prior statements are not true <b>and</b> the current statement is true.</li>\n",
|
||||||
|
" <li>The code within an <b>else</b> statement applies if all prior statements are not true.</li>\n",
|
||||||
|
"</ul>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>4.1 For Loops</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"A <b>for loop</b> is used when you're going to be repeating a block of code a predetermined number of times. The format is simple enough: <b>for</b> an index <b>in</b> a list:. The block of code that you'll then be running <b>must be indented</b>: either use Tab or press Spacebar four times at the start of each line. (This is the price we pay for not having to end statements with a semicolon or something similar.)\n",
|
||||||
|
"\n",
|
||||||
|
"The index we refer to here is just a counter that's going to keep track of how many times the loop has been run. Often we just call this index 'i', but you can name it whatever you like. This index will be assigned to each individual item in the list until we run out of list items."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Let's try an example. First let's define a list!\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# Now let's print each value within that list using a for loop.\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Note that the index variable changes variable type as it goes down the list, from integer to float to string to integer. Technically, this index should be called an <b>iterator</b>, and iterators are one example of an <b>object</b>, which we'll see in more detail when we get into object-oriented programming later in this course.\n",
|
||||||
|
"\n",
|
||||||
|
"Sometimes you'll want the iterator to just count the elements in a list, rather than actually taking on their values. For this, the range() function comes in handy: you specify the size of the list you want, and it will create a new list counting the number of elements. That is, range(n) returns [0,1,2,...,n-1]."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# You can use the range function in a for loop. In this case, i is an integer for every step of the loop.\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Let's try a meteorological example of a for loop. Let's say you have 10 temperature measurements in Celsius and want them to be converted to Fahrenheit. A for loop is a great way to do this!"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# First, let's define our initial 10 temperature measurements.\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# Next, we'll want to loop over all values in this list.\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"\n",
|
||||||
|
" \n",
|
||||||
|
"# Did it work? Let's check.\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Note that, for this example, we had to use the range() function, because we needed to know the index of each temperature measurement we were in the process of converting. If we didn't know how many elements were in temp, we could have used range(len(temp)) instead of range(10). "
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"The range() function is also useful for counting based on a particular pattern, using the format <b>range(first value,final value,increment)</b>. Remember that the first value is always <b>inclusive</b> and the final value is always <b>exclusive</b>!"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# Let's convert the same dataset from Celsius to Fahrenheit, but this time we'll only convert\n",
|
||||||
|
"# every second temperature, going backwards.\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"As a side note, using an integer in a function in a way that makes that function less versatile (for instance, range(10) above means the loop will only work for lists with 10 elements) is often called <b>hardcoding</b> and is good to avoid when you can. If instead we used range(len(temp)), it wouldn't matter how many elements there were in the list: our loop would still work.\n",
|
||||||
|
"\n",
|
||||||
|
"It's also very possible to combine the logical constructs from yesterday's class with a loop."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Let's use our new Fahrenheit temperatures to make some statements!\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>4.2 While Loops</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"A <b>while</b> loop lets you loop an indefinite number of times. This comes in handy if we don't yet know how many times we want to repeat a process (for instance, adding a random number to a running total until we hit a particular target value). The syntax is simple: <b>while \\<condition\\>:</b>. The indented code following the while line will be executed repeatedly while \\<condition\\> evaluates as True."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Let's do a simple example of a while loop that will print the integers one through nine.\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"That first line (a = 1) is known as an <b>initialization</b> and is a key part of a while loop: if we didn't have a value of a to start with, we couldn't evaluate whether the while statement was True or False. The last line (a = a + 1) is known as an <b>incrementation</b> and ensures that we're not just doing the same check over and over again."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Here's an example of a while loop that will not run because the while condition is always False.\n",
|
||||||
|
"\n",
|
||||||
|
"# There won't be an error message, but the loop will never run.\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"What if the while statement is always True? Then the while statement will go on forever. This... is a problem. If you suspect you may be caught in an infinite loop, you can often hit CTRL-C to stop the process, or hit the stop button in a Jupyter notebook.\n",
|
||||||
|
"\n",
|
||||||
|
"Often this problem emerges because the incrementation step (in the example above, a = a + 1) gets forgotten."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# We're not going to run an infinite-loop example here because it may crash your web browser. But it happens!"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<b>An Example!</b>\n",
|
||||||
|
"\n",
|
||||||
|
"Using 1) a <b>for</b> loop, and 2) a <b>while</b> loop, write code that will count integers backwards from 10 to 1."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"tags": []
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# For loop!\n",
|
||||||
|
"\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"tags": []
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# While Loop!\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>TAKE-HOME POINTS</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li>A <b>for loop</b> lets you repeat an operation a specified number of times.</li>\n",
|
||||||
|
" <li>Indentation is critical for lists in Python.</li>\n",
|
||||||
|
" <li>The range() function will create a list of all values up to the specified integer.</li>\n",
|
||||||
|
" <li>Hardcoding is the act of (often unnecessarily) restricting a piece of code so it only works under specific circumstances.</li>\n",
|
||||||
|
" <li>A <b>while loop</b> lets you repeat an operation until a particular condition is met.</li>\n",
|
||||||
|
" <li>The index in a while loop must be initialized and care should be taken to avoid infinite loops.</li>\n",
|
||||||
|
"</ul>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3 (ipykernel)",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python3"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 3
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython3",
|
||||||
|
"version": "3.9.6"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 4
|
||||||
|
}
|
||||||
380
python/atms-310/notebooks/Week 02 M.ipynb
Executable file
380
python/atms-310/notebooks/Week 02 M.ipynb
Executable file
@ -0,0 +1,380 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h1>2. Lists and Dictionaries</h1>\n",
|
||||||
|
"<h2>10/02/23</h2>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>2.0 Last Time...</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li>Python has a variety of data types, many of which we saw today!</li>\n",
|
||||||
|
" <li>An <b>integer</b> variable is a number with no decimal point.</li>\n",
|
||||||
|
" <li>A <b>floating point</b> variable is a number with a decimal point</li>\n",
|
||||||
|
" <li>A <b>string</b> variable is text.</li>\n",
|
||||||
|
" <li>A <b>Boolean</b> variable can take on the values <b>True</b> and <b>False</b>.</li>\n",
|
||||||
|
" <li>A <b>NoneType</b> variable can take on the value <b>None</b>.</li>\n",
|
||||||
|
" <li>Python uses dynamic typing, which means you don't need to define a variable's type when you first use that variable.</li>\n",
|
||||||
|
" <li>The type() command lets you see what type a given variable is. int(), float(), and str() can be used to convert to different variable types.</li>\n",
|
||||||
|
" <li>Combining a float and an integer results in a float.</li>\n",
|
||||||
|
" <li>Combining a string and an integer or float results in a TypeError.</li>\n",
|
||||||
|
" <li>Floats are often prone to rounding errors.</li>\n",
|
||||||
|
" <li><b>and</b> and <b>or</b> can be used to combine Boolean variables.</li>\n",
|
||||||
|
"</ul>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>2.1 Lists and Tuples</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"A <b>list</b> is simply an ordered sequence of values, similar to arrays in other programming languages. Each element of a list can be assigned to anything (you can have a mix of variable types within a given list), including another list.\n",
|
||||||
|
"\n",
|
||||||
|
"Lists are defined using square brackets (\"[]\"), and individual elements have commas between them.\n",
|
||||||
|
"\n",
|
||||||
|
"Counting in Python starts with <b>0</b>. This can lead to some confusion, but always remember that the first element in a list is actually element 0, the second is actually element 1, and so on.\n",
|
||||||
|
"\n",
|
||||||
|
"You can also count from the end, so that element <b>-1</b> is actually the last element in a list, <b>-2</b> is the second-last element, and so on.\n",
|
||||||
|
"\n",
|
||||||
|
"Finally, to find the length of a list, use the len() command."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Create a complicated list that has a list as one of its elements.\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# As a side note, if you want to split a long line of code across\n",
|
||||||
|
"# multiple lines, just use a backslash with nothing after it:\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Find the length of this list.\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# To get a value from a list within a list:\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Likewise, you can make use of the reverse numbering:\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"A list can be sliced to just obtain a subsection using a colon to separate the lower and upper limits. The lower limit of the range is <b>inclusive</b> and the upper range is <b>exclusive</b>, so that a [1:3] subset will consist of the second and third elements in a list."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Values within a list can be changed; lists are <b>mutable</b>. Changing by assignment is the most basic way to do this."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Let's change 'hello' to 'goodbye' in the original list.\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Lists in python actually have some built-in functions called <b>methods</b> that can change the properties of the list. We'll talk about these more when we get into object-oriented programming later in this course, but for now, we'll consider <b>insert</b>, <b>remove</b> and <b>append</b>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# 'Insert' places the requested element into the list \n",
|
||||||
|
"# before the specified element of the list.\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# 'Remove' gets rid of the first occurrence of the specified element.\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Append adds the specified element to the end of the list.\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"To an extent, you can treat an individual string as a list."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"A <b>tuple</b> is simply a list that cannot be changed (i.e., <b>immutable</b>), and an error will be returned by Python if you do attempt to change an element within a tuple. Defining a tuple is exactly the same as defining a list, except that you use parentheses instead of square brackets."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Create a simple tuple:\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# But note that you cannot change a value within a tuple.\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>2.2 Dictionaries</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"A dictionary, as opposed to a list/tuple, is an <b>unordered</b> list: elements are referenced by <b>keys</b>, not position. A key can be anything, as can the value it refers to.\n",
|
||||||
|
"\n",
|
||||||
|
"A dictionary is delimited by curly braces (\"{}\"), and each element is a key:value pair separated by a colon. In order to refer to a particular element in a dictionary, we proceed much as we do with a list, except using a key instead of an element address."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Let's create a dictionary similar to our list from earlier.\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Here, our keys are 'value_a','value_b',and 'value_c', and we can refer to \n",
|
||||||
|
"# each of them accordingly.\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Just like lists, dictionaries have <b>methods</b> - and again, we'll go over this in more detail as we get to the object-oriented programming part of this course, but for now, consider <b>keys</b> and <b>values</b>."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# \"Keys\" returns a list of all the keys of a.\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# \"Values\" returns a list of all the values of a.\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# To check whether a particular key is used in a dictionary, use the following\n",
|
||||||
|
"# syntax:\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Note that <b>keys</b> and <b>values</b> will return key:value pairs in no particular order. To make sure one corresponds to the other, you can first sort the dictionary into a desired order using something like <b>sorted</b>, which we'll explore soon."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h1>TAKE-HOME POINTS</h1>\n",
|
||||||
|
"\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li>A list is a <b>mutable</b>, <b>ordered</b> sequence of elements.</li>\n",
|
||||||
|
" <li>Python counts starting with 0, not 1.</li>\n",
|
||||||
|
" <li>You can also count backwards from the end of a list using negative numbers.</li>\n",
|
||||||
|
" <li>A list can be sliced, where the slice is defined by a range that has an inclusive lower bound and an exclusive upper bound.</li>\n",
|
||||||
|
" <li>Values in a list can be changed by assignment or by particular methods.</li>\n",
|
||||||
|
" <li>A tuple is an <b>immutable</b>, <b>ordered</b> sequence of elements.</li>\n",
|
||||||
|
" <li>A dictionary is a <b>mutable</b>, <b>unordered</b> sequence of elements consisting of key:value pairs.</li>\n",
|
||||||
|
"</ul>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3 (ipykernel)",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python3"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 3
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython3",
|
||||||
|
"version": "3.10.10"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 4
|
||||||
|
}
|
||||||
427
python/atms-310/notebooks/Week 02 W.ipynb
Executable file
427
python/atms-310/notebooks/Week 02 W.ipynb
Executable file
@ -0,0 +1,427 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h1>3. Functions and Logic</h1>\n",
|
||||||
|
"<h2>10/04/23</h2>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>3.0 Last Time...</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li>A list is a <b>mutable</b>, <b>ordered</b> sequence of elements.</li>\n",
|
||||||
|
" <li>Python counts starting with 0, not 1.</li>\n",
|
||||||
|
" <li>You can also count backwards from the end of a list using negative numbers.</li>\n",
|
||||||
|
" <li>A list can be sliced, where the slice is defined by a range that has an inclusive lower bound and an exclusive upper bound.</li>\n",
|
||||||
|
" <li>Values in a list can be changed by assignment or by particular methods.</li>\n",
|
||||||
|
" <li>A tuple is an <b>immutable</b>, <b>ordered</b> sequence of elements.</li>\n",
|
||||||
|
" <li>A dictionary is a <b>mutable</b>, <b>unordered</b> sequence of elements consisting of key:value pairs.</li>\n",
|
||||||
|
"</ul>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>3.1 Functions</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"A <b>function</b> is a self-contained block of code that can be \"called\" in any other code. It can take user-specified input and return output (which is generally a single output value: you can put multiple outputs into a list).\n",
|
||||||
|
"\n",
|
||||||
|
"To create a function, we start with a <b>def</b> statement that defines the name of the function and then follows with a list of input arguments in parentheses, followed by a colon.\n",
|
||||||
|
"\n",
|
||||||
|
"All the code that you want to be executed within a function should be indented (by default, this is typically indented by four spaces). The amount of whitespace before a command in Python matters! Everything indented together will be run together; there's no need to specify the end of the function."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 65,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# You can start by defining a function that calculates the surface area\n",
|
||||||
|
"# of a cylinder. \n",
|
||||||
|
"# This can go in its own file so that you can refer to it in the future\n",
|
||||||
|
"# from any code you may want to run.\n",
|
||||||
|
"def area(radius, height):\n",
|
||||||
|
" a = 2*3.14*radius**2 + 2*3.14*radius*height\n",
|
||||||
|
" return a\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# Basically, this function is called 'area' and takes as input two variables\n",
|
||||||
|
"# called 'radius' and 'height' from the user. \n",
|
||||||
|
"# It calculates the surface area of a cylinder, then outputs or 'returns' \n",
|
||||||
|
"# that area to the original code.\n",
|
||||||
|
"\n",
|
||||||
|
"# Running this block of code now will output nothing; you've just defined\n",
|
||||||
|
"# the function."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 66,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"94.2\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Now, try calling the function using a radius of 3 and a height of 2.\n",
|
||||||
|
"print(area(3,2))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 67,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"94.2\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# An even shorter version of that function would be:\n",
|
||||||
|
"def area(radius, height):\n",
|
||||||
|
" return 2*3.14*radius**2 + 2*3.14*radius*height\n",
|
||||||
|
"\n",
|
||||||
|
"print(area(3,2))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"The arguments in this example ('radius' and 'height') are what's known as <b>positional arguments</b>, meaning that it knows the first argument corresponds to the radius and the second argument corresponds to the height.\n",
|
||||||
|
"\n",
|
||||||
|
"Alternatively, you can use what are known as <b>keyword arguments</b>."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 68,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"94.2\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Can write the arguments out of order if we're using keywords!\n",
|
||||||
|
"print(area(height=2, radius=3))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 69,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"62.8\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Note that this doesn't work with positional arguments:\n",
|
||||||
|
"print(area(2,3))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"You can facilitate long lists of arguments by treating positional arguments like lists and treating keyword arguments like dictionaries. To do this, in the function call, you just need to place an asterisk (\\*) before the list with positional arguments and two asterisks (\\*\\*) before the list with keyword arguments."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 70,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"94.2\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Call the function using a list of positional arguments.\n",
|
||||||
|
"positional = [3,2] # plugging values from the list \"positional\" into area function\n",
|
||||||
|
"print(area(*positional))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 71,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"94.2\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Call the function using a dictionary of keyword arguments.\n",
|
||||||
|
"\n",
|
||||||
|
"keyword = {'height':2, 'radius':3}\n",
|
||||||
|
"print(area(**keyword))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 72,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"94.2\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Call the function using a combo of positional and keyword arguments.\n",
|
||||||
|
"positional = [3]\n",
|
||||||
|
"keyword = {'height':2}\n",
|
||||||
|
"print(area(*positional,**keyword))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"This seems like a silly way of going about it, but if you're passing dozens or hundreds of variables to a particular function, it definitely makes life easier!"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>3.2 Logical Constructs</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"Logic in Python is handled through <b>if statements</b>. The general idea behind an if statement is that we check whether something is true: if it is, we then execute certain code before continuing.\n",
|
||||||
|
"\n",
|
||||||
|
"If statements are formatted by writing <b>if</b> and then some condition that must be met, followed by a colon. The block of code we wish to execute if the statement is true must all be indented together."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 73,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"ass\n",
|
||||||
|
"booty\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Write a code that checks whether a given variable is equal to 3.\n",
|
||||||
|
"a = 3\n",
|
||||||
|
"if a == 3:\n",
|
||||||
|
" print('ass')\n",
|
||||||
|
"print('booty')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 74,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# If the condition is not true, the code ignores what's indented.\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"You can also specify what will be done if your conditional statement is not true by using <b>else:</b>."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 75,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"hell no\n",
|
||||||
|
"buttocks\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Now, if the condition is not true, the code continues with what follows\n",
|
||||||
|
"# the else statement.\n",
|
||||||
|
"a = 2\n",
|
||||||
|
"if a == 3:\n",
|
||||||
|
" print('yes!')\n",
|
||||||
|
"else:\n",
|
||||||
|
" print('hell no')\n",
|
||||||
|
"\n",
|
||||||
|
"print('buttocks')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Want to deal with more than one scenario? Use <b>elif</b>, which is short for <b>else if:</b>. In other words, if the previous condition is not true, but this new condition is true, do this instead."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 76,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"its 3\n",
|
||||||
|
"end\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"a = 3\n",
|
||||||
|
"if a == 3:\n",
|
||||||
|
" print('its 3')\n",
|
||||||
|
"elif a == 2:\n",
|
||||||
|
" print('its 2')\n",
|
||||||
|
"else: print('it aint 2 or 3')\n",
|
||||||
|
"\n",
|
||||||
|
"print('end')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Pay close attention to the indentation in the above code!"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<b>An example!</b>\n",
|
||||||
|
"\n",
|
||||||
|
"Write an if/elif/else statement in the box below to check whether a particular variable is positive, negative, or equal to zero. Each possibility should print a string statement: \"I am positive.\", \"I am negative.\", or \"I am zero.\"\n",
|
||||||
|
"\n",
|
||||||
|
"Try testing it with different values to make sure it works!\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 6,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"its negative\n",
|
||||||
|
"end\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"d = input('enter a number')\n",
|
||||||
|
"f = int(d)\n",
|
||||||
|
"if f == 0:\n",
|
||||||
|
" print('its zero')\n",
|
||||||
|
"elif f < 0:\n",
|
||||||
|
" print('its negative')\n",
|
||||||
|
"elif f > 0:\n",
|
||||||
|
" print('its positive')\n",
|
||||||
|
"print('end')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>TAKE-HOME POINTS</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li>A <b>function</b> is a block of code that can be called.</li>\n",
|
||||||
|
" <li>Functions can be called using either positional or keyword arguments.</li>\n",
|
||||||
|
" <li>Positional arguments can be described via lists and keyword arguments can be described via dictionaries.</li>\n",
|
||||||
|
" <li>Python uses if statements for logical constructs.</li>\n",
|
||||||
|
" <li>The code within an <b>if</b> statement is run if the current statement is true.</li>\n",
|
||||||
|
" <li>The code within an <b>elif</b> statement applies if prior statements are not true <b>and</b> the current statement is true.</li>\n",
|
||||||
|
" <li>The code within an <b>else</b> statement applies if all prior statements are not true.</li>\n",
|
||||||
|
"</ul>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3 (ipykernel)",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python3"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 3
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython3",
|
||||||
|
"version": "3.9.6"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 4
|
||||||
|
}
|
||||||
671
python/atms-310/notebooks/Week 03 F.ipynb
Executable file
671
python/atms-310/notebooks/Week 03 F.ipynb
Executable file
@ -0,0 +1,671 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h1>7. Testing Inside Arrays</h1>\n",
|
||||||
|
"\n",
|
||||||
|
"<h2>10/13/2023</h2>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>7.0 Last Time...</h2>\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li>An array is NumPy's version of a list, which allows you to work with matrices.</li>\n",
|
||||||
|
" <li>All elements of an array are of the same type.</li>\n",
|
||||||
|
" <li>You can either create a new array or convert an existing list into one.</li>\n",
|
||||||
|
" <li>The zeros() function is useful for initializing an array when you know the shape and size but not the contents.</li>\n",
|
||||||
|
" <li>The arange() function serves a similar purpose to the range() function with lists.</li>\n",
|
||||||
|
" <li>Similar to lists, arrays can be sliced, but arrays can be sliced across each of their dimensions.</li>\n",
|
||||||
|
"</ul>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 3,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[[0. 0. 0. 0. 0.]\n",
|
||||||
|
" [0. 0. 0. 0. 0.]\n",
|
||||||
|
" [0. 0. 0. 0. 0.]\n",
|
||||||
|
" [0. 0. 0. 0. 0.]]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"#1. What is the code to create a 4-row, 5-column array of zeros and assign it to the variable a?\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"a = np.zeros((4,5))\n",
|
||||||
|
"print(a)\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"#2. Using array a from above, answer the following questions:\n",
|
||||||
|
"\n",
|
||||||
|
"a = np.array([[2,3.2,5.5,-6.4,-2.2,2.4],\n",
|
||||||
|
" [1, 22, 4, 0.1, 5.3, -9],\n",
|
||||||
|
" [3, 1,2.1, 21, 1.1, -2]])\n",
|
||||||
|
"\n",
|
||||||
|
"#a. What is a[:,3]?\n",
|
||||||
|
"\n",
|
||||||
|
"#b. What is a[1:4,0:2]?\n",
|
||||||
|
"\n",
|
||||||
|
"#c. What will b = a[1:,2] do?\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>7.1 Array Inquiry</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"There are a series of functions within NumPy that we can use to gain information about a given array.\n",
|
||||||
|
"\n",
|
||||||
|
"To return the <b>shape</b> of an array (i.e., its dimensions), we use numpy.shape().\n",
|
||||||
|
"\n",
|
||||||
|
"To return the <b>number of dimensions</b> of an array, we use numpy.ndim().\n",
|
||||||
|
"\n",
|
||||||
|
"To return the <b>number of elements</b> in an array, we use numpy.size()."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 17,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"(3, 6)\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Don't forget to import numpy!\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"\n",
|
||||||
|
"a = np.array([[2,3.2,5.5,-6.4,-2.2,2.4],\n",
|
||||||
|
" [1, 22, 4, 0.1, 5.3, -9],\n",
|
||||||
|
" [3, 1,2.1, 21, 1.1, -2]])\n",
|
||||||
|
"print(np.shape(a))\n",
|
||||||
|
"\n",
|
||||||
|
"# This is the example array from yesterday's lecture.\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# Array shape.\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 5,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"2\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Array number of dimensions.\n",
|
||||||
|
"print(np.ndim(a))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 6,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"18\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Array number of elements.\n",
|
||||||
|
"print(np.size(a))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"If you want to search within an array for the location of values matching a particular criterion (useful when you have a giant dataset!), you can use numpy.where()."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 7,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"(array([0, 0, 1, 2]), array([3, 4, 5, 5]))\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Search for all places within the array with negative values.\n",
|
||||||
|
"print(np.where(a < 0))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Once you have the locations where the criterion is met, you can then modify only those values!"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 15,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# This code will look for all the negative values in the array and change them to positive.\n",
|
||||||
|
"c = np.where(a<0)\n",
|
||||||
|
"a[c] = np.abs(a[c])\n",
|
||||||
|
"print(a[c])"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"You can also create a list of all values within an array matching a particular criterion.\n",
|
||||||
|
"\n",
|
||||||
|
"(We'll see more on array testing soon...)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 16,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"print(a[a<0])"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>7.2 Array Manipulation</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"Rather than just finding things out about arrays, NumPy also allows you to manipulate arrays. Some of these come from matrix algebra, but others are just ways to shift the data around into useable formats. Here are a few examples:\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li><b>numpy.reshape()</b>: reshape an array to the desired dimensions.</li>\n",
|
||||||
|
" <li><b>numpy.transpose()</b>: transpose an array (flip rows and columns, for example).</li>\n",
|
||||||
|
" <li><b>numpy.ravel()</b>: \"flatten\" an array back into a 1D vector.</li>\n",
|
||||||
|
" <li><b>numpy.concatenate()</b>: concatenate arrays.</li>\n",
|
||||||
|
" <li><b>numpy.repeat()</b>: repeat array elements.</li>\n",
|
||||||
|
"</ul>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 23,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[0 1 2 3 4 5]\n",
|
||||||
|
"[0 1 2 3 4 5 6 7]\n",
|
||||||
|
"[[ 2. 3.2 5.5 -6.4 -2.2 2.4]\n",
|
||||||
|
" [ 1. 22. 4. 0.1 5.3 -9. ]\n",
|
||||||
|
" [ 3. 1. 2.1 21. 1.1 -2. ]]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Let's create some arrays to play with.\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"z = np.arange(6)\n",
|
||||||
|
"x = np.arange(8)\n",
|
||||||
|
"a = np.array([[2,3.2,5.5,-6.4,-2.2,2.4],\n",
|
||||||
|
" [1, 22, 4, 0.1, 5.3, -9],\n",
|
||||||
|
" [3, 1,2.1, 21, 1.1, -2]])\n",
|
||||||
|
"\n",
|
||||||
|
"print(z)\n",
|
||||||
|
"print(x)\n",
|
||||||
|
"print(a)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 25,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[[0 1 2]\n",
|
||||||
|
" [3 4 5]]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# First, reshape a from a 1x6 to a 2x3 array:\n",
|
||||||
|
"print(np.reshape(z,(2,3)))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 27,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[[ 2. 1. 3. ]\n",
|
||||||
|
" [ 3.2 22. 1. ]\n",
|
||||||
|
" [ 5.5 4. 2.1]\n",
|
||||||
|
" [-6.4 0.1 21. ]\n",
|
||||||
|
" [-2.2 5.3 1.1]\n",
|
||||||
|
" [ 2.4 -9. -2. ]]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Next, transpose c from a 3x6 to a 6x3 array:\n",
|
||||||
|
"print(np.transpose(a))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 28,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[ 2. 3.2 5.5 -6.4 -2.2 2.4 1. 22. 4. 0.1 5.3 -9. 3. 1.\n",
|
||||||
|
" 2.1 21. 1.1 -2. ]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Try \"flattening\" c into a 1-D array:\n",
|
||||||
|
"print(np.ravel(a))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 30,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[0 1 2 3 4 5 0 1 2 3 4 5 6 7]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Now try concatenating (combining) the two 1-D arrays:\n",
|
||||||
|
" # This is another function that needs a double-parentheses\n",
|
||||||
|
" # because there are other options that can be changed in the function.\n",
|
||||||
|
" \n",
|
||||||
|
" \n",
|
||||||
|
"print(np.concatenate((z,x)))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 31,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[0 0 0 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Print array a and repeat each value 3 times:\n",
|
||||||
|
"\n",
|
||||||
|
"print(np.repeat(z,3))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>7.3 Array Operations</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"<h3>7.3.1 Looping (slow and steady)</h3>\n",
|
||||||
|
"\n",
|
||||||
|
"As an example of what's going on \"under the hood\", one way you can perform operations on an array is simply to loop through every single value within that array and perform the operation on each element.\n",
|
||||||
|
"\n",
|
||||||
|
"As you might imagine, this can get <i>tedious</i>."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 38,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"(2, 8)\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Let's create two arrays and multiply them together, element by element.\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"\n",
|
||||||
|
"a = np.array([[2,3,2,5,6,7,45,34],\n",
|
||||||
|
" [123,345,634,3234,234,2,432,4]])\n",
|
||||||
|
"b = np.array ([[123,534,234,423,3,2,23,23],[234,543,645,234,6,23,54,9]])\n",
|
||||||
|
" \n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# Let's now get the shape of the arrays (they have the same shape, so we'll just get a's shape).\n",
|
||||||
|
"print(np.shape(a))\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 34,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"(2, 8)\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Next, let's create a matrix of zeros in the shape of the element-by-element product we eventually want.\n",
|
||||||
|
"ashape = np.shape(a)\n",
|
||||||
|
"print(ashape)\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Finally, we loop over all x values and all y values using arange.\n",
|
||||||
|
"for i in np.arange(ashape[0]):\n",
|
||||||
|
" for j in np.arange(ashape[1]):\n",
|
||||||
|
" pr\n",
|
||||||
|
"# ok whatever\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h3>7.3.2 Array Syntax (quick and efficient)</h3>\n",
|
||||||
|
"\n",
|
||||||
|
"...alternatively, we could do this using built-in syntax that operates on the entire array at once."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 39,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[[ 246 1602 468 2115 18 14 1035 782]\n",
|
||||||
|
" [ 28782 187335 408930 756756 1404 46 23328 36]]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"productab = a*b\n",
|
||||||
|
"print(a*b)\n",
|
||||||
|
"\n",
|
||||||
|
" # Note that this method assumes the arrays are the same size.\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Well, okay. That does seem a little easier."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 42,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[0 1 2 3 4 5 6 7 8 9]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Let's try another example. Start with a simple 1-D array \n",
|
||||||
|
"# that's just the integers from 0 to 9. \n",
|
||||||
|
"u = np.arange(10)\n",
|
||||||
|
"print(u)\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# Now try some operations on it!"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 43,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[ 0 2 4 6 8 10 12 14 16 18]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"print(u*2)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>7.4 Testing Inside an Array</h2>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Let's return to logical testing within an array. NumPy has several alternative ways to do logical tests: for instance, we can use <b>\\></b> as 'greater than', or we can use <b>numpy.greater()</b> for the same result."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 47,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[0 1 2 3 4 5]\n",
|
||||||
|
"[False False False False True True]\n",
|
||||||
|
"[False False False False True True]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"import numpy\n",
|
||||||
|
"t = np.arange(6)\n",
|
||||||
|
"print(t)\n",
|
||||||
|
"print(t > 3)\n",
|
||||||
|
"\n",
|
||||||
|
" # This uses a more traditional logical format.\n",
|
||||||
|
" # This uses NumPy's built-in function.\n",
|
||||||
|
"\n",
|
||||||
|
"print(np.greater(t,3))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Unfortunately, the same doesn't apply to Python's built-in <b>and</b> and <b>or</b> functions; in those cases, you have to use NumPy's numpy.logical_and() and numpy.logical_or() functions."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 48,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"ename": "ValueError",
|
||||||
|
"evalue": "The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()",
|
||||||
|
"output_type": "error",
|
||||||
|
"traceback": [
|
||||||
|
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
|
||||||
|
"\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)",
|
||||||
|
"\u001b[1;32m/Users/nik/data/python/notebooks/Week 03 F.ipynb Cell 37\u001b[0m line \u001b[0;36m3\n\u001b[1;32m <a href='vscode-notebook-cell:/Users/nik/data/python/notebooks/Week%2003%20F.ipynb#X51sZmlsZQ%3D%3D?line=0'>1</a>\u001b[0m \u001b[39m# Let's write code that outputs 'True' only when a > 1 and a <= 3.\u001b[39;00m\n\u001b[1;32m <a href='vscode-notebook-cell:/Users/nik/data/python/notebooks/Week%2003%20F.ipynb#X51sZmlsZQ%3D%3D?line=1'>2</a>\u001b[0m w \u001b[39m=\u001b[39m np\u001b[39m.\u001b[39marange(\u001b[39m6\u001b[39m)\n\u001b[0;32m----> <a href='vscode-notebook-cell:/Users/nik/data/python/notebooks/Week%2003%20F.ipynb#X51sZmlsZQ%3D%3D?line=2'>3</a>\u001b[0m \u001b[39mprint\u001b[39m((w\u001b[39m>\u001b[39m\u001b[39m1\u001b[39m) \u001b[39mand\u001b[39;00m (a\u001b[39m<\u001b[39m\u001b[39m=\u001b[39m\u001b[39m3\u001b[39m))\n",
|
||||||
|
"\u001b[0;31mValueError\u001b[0m: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Let's write code that outputs 'True' only when a > 1 and a <= 3.\n",
|
||||||
|
"w = np.arange(6)\n",
|
||||||
|
"print((w>1) and (a<=3))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 49,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[False False True True False False]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"print(np.logical_and(t>1,t<=3))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>7.5 Take-Home Points</h2>\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li>You can use functions within NumPy to find the shape, number of dimensions, and number of elements in any array.</li>\n",
|
||||||
|
" <li><b>numpy.where()</b> will let you find the locations of elements within an array that meet a specified criterion.</li>\n",
|
||||||
|
" <li>Some functions within NumPy allow you to manipulate arrays, such as reshaping, transposing, \"unraveling\", concatenation, and repeating individual array elements.</li>\n",
|
||||||
|
" <li>When you're in a situation with multiple nested loops, often you can instead perform all operations a lot more easily by using array syntax.</li>\n",
|
||||||
|
" <li>Mathematical operations act on arrays elementwise.</li>\n",
|
||||||
|
" <li>When testing within an array, <b>and</b> and <b>or</b> cannot be used; instead, use NumPy's built-in functions.</li>\n",
|
||||||
|
"</ul>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3 (ipykernel)",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python3"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 3
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython3",
|
||||||
|
"version": "3.11.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 4
|
||||||
|
}
|
||||||
335
python/atms-310/notebooks/Week 03 M.ipynb
Executable file
335
python/atms-310/notebooks/Week 03 M.ipynb
Executable file
@ -0,0 +1,335 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h1>5. Modules and Exception Handling</h1>\n",
|
||||||
|
"<h2>10/09/2023</h2>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>5.0 Last Time...</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li>A <b>for loop</b> lets you repeat an operation a specified number of times.</li>\n",
|
||||||
|
" <li>Indentation is critical for loops in Python.</li>\n",
|
||||||
|
" <li>The range() function will create a list of all values up to the specified integer.</li>\n",
|
||||||
|
" <li>Hardcoding is the act of (often unnecessarily) restricting a piece of code so it only works under specific circumstances.</li>\n",
|
||||||
|
" <li>A <b>while loop</b> lets you repeat an operation until a particular condition is met.</li>\n",
|
||||||
|
" <li>The index in a while loop must be initialized and care should be taken to avoid infinite loops.</li>\n",
|
||||||
|
"</ul>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>5.1 Modules</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"A <b>module</b> is just a library of Python source code files that will give you access to new (frequently more specialized) functions.\n",
|
||||||
|
"\n",
|
||||||
|
"To import a module, the syntax is simply: <b>import \\<module name\\></b>."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 2,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"-0.7568024953079283\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# An extremely useful module in the atmospheric science world is NumPy.\n",
|
||||||
|
"# This package lets you use a variety of mathematical (and array-based) functions and variables.\n",
|
||||||
|
"import numpy\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# As soon as the module is imported, you have access to all its contents.\n",
|
||||||
|
"\n",
|
||||||
|
"# To refer to a function or variable within numpy, just follow it with a \n",
|
||||||
|
"# period, then the function or variable in question.\n",
|
||||||
|
"\n",
|
||||||
|
"# As an example, numpy will let you calculate the sine of a given number.\n",
|
||||||
|
"a = numpy.sin(4)\n",
|
||||||
|
"print(a)\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Some modules have what are called <b>submodules</b> that can be referred to in a similar way. For instance, the module NumPy has a submodule called ma, which in turn has particular functions defined within it. If you wanted to run the <b>array</b> function inside the <b>ma</b> submodule inside the <b>NumPy</b> module, it would look like <b>numpy.ma.array</b>.\n",
|
||||||
|
"\n",
|
||||||
|
"Modules have detailed documentation (typically easily found via Google) that will let you browse all the available functions at your disposal. This instance of Jupyter has several modules preinstalled; they may be missing if you try running them on a Python build at home. Fortunately, there are generally helpful instructions online for downloading new modules so they can be imported into your code."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 1,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"data": {
|
||||||
|
"text/plain": [
|
||||||
|
"-0.7568024953079282"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"execution_count": 1,
|
||||||
|
"metadata": {},
|
||||||
|
"output_type": "execute_result"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# If you find yourself typing the same module name again and again, \n",
|
||||||
|
"# you can rename it to something a little quicker!\n",
|
||||||
|
"\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"\n",
|
||||||
|
"a = np.sin(4)\n",
|
||||||
|
"a"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"As a meteorological example, let's return to our list of Celsius temperatures from yesterday. NumPy will enable us to easily calculate the maximum and minimum temperatures."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 2,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"The maximum temperature is 36.5 and the minimum temperature is 13.5.\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# First, here's our temperature list.\n",
|
||||||
|
"\n",
|
||||||
|
"temp = [23.5,24.5,18.0,26.8,17.7,17.0,27.1,24.6,13.5,36.5]\n",
|
||||||
|
"\n",
|
||||||
|
"# Let's import NumPy.\n",
|
||||||
|
"\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"\n",
|
||||||
|
"# Now, use the max() and min() functions within the NumPy module\n",
|
||||||
|
"# to calculate the maximum and minimum temperatures.\n",
|
||||||
|
"\n",
|
||||||
|
"maxT = np.max(temp)\n",
|
||||||
|
"minT = np.min(temp)\n",
|
||||||
|
"\n",
|
||||||
|
"# We can even output a nice sentence summing it up!\n",
|
||||||
|
"\n",
|
||||||
|
"print(\"The maximum temperature is \"+str(maxT)+\" and the minimum temperature is \"+str(minT)+\".\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<b>An example!</b>\n",
|
||||||
|
"\n",
|
||||||
|
"In the box below, write a block of code that will apply a NumPy mathematical function of your choice to the list of temperatures <b>(temp)</b> above: https://numpy.org/doc/stable/reference/routines.math.html. Don't forget to include your module import statement!"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 1,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[-0.99808203 -0.59135753 -0.75098725 0.9953511 -0.91258245 -0.96139749\n",
|
||||||
|
" 0.92243282 -0.50789659 0.80378443 -0.93171689]\n",
|
||||||
|
"[-0.06190529 0.80640949 0.66031671 -0.09631292 0.40889274 -0.27516334\n",
|
||||||
|
" -0.38615761 0.86141805 0.59492066 0.36318541]\n",
|
||||||
|
"[ 16.12272495 -0.73332164 -1.13731371 -10.33455467 -2.23183823\n",
|
||||||
|
" 3.49391565 -2.38874697 -0.58960523 1.35107835 -2.56540287]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"temp = [23.5,24.5,18.0,26.8,17.7,17.0,27.1,24.6,13.5,36.5]\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"\n",
|
||||||
|
"# Mathematical function #1.\n",
|
||||||
|
"print(np.sin(temp))\n",
|
||||||
|
"\n",
|
||||||
|
"# Mathematical function #2.\n",
|
||||||
|
"print(np.cos(temp))\n",
|
||||||
|
"print(np.tan(temp))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>5.2 Exception Handling</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"An \"exception\" is a very polite way of saying \"error\" in programming-speak. Often we use an if statement to determine whether something is going to cause a problem, and then use a <b>raise</b> statement to tell the code to stop and output a particular error."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 2,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"6\n",
|
||||||
|
"12.566370614359172\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Let's say we have a code that will attempt to calculate the area of a circle\n",
|
||||||
|
"# based on its radius.\n",
|
||||||
|
"# It works well for positive values of radius, but we want to allow for the\n",
|
||||||
|
"# possibility that someone might enter a negative radius.\n",
|
||||||
|
"\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"\n",
|
||||||
|
"def circle_area(radius):\n",
|
||||||
|
" if radius < 0:\n",
|
||||||
|
" raise ValueError('Radius cannot be negative, you fool!')\n",
|
||||||
|
" area = np.pi * (radius**2)\n",
|
||||||
|
" return area\n",
|
||||||
|
"\n",
|
||||||
|
"def quadarea(base, height):\n",
|
||||||
|
" if base < 0:\n",
|
||||||
|
" raise ValueError('enter a POSITIVE number')\n",
|
||||||
|
" elif height < 0:\n",
|
||||||
|
" raise ValueError('POSITIVE integer please')\n",
|
||||||
|
" x = base*height\n",
|
||||||
|
" return x\n",
|
||||||
|
"# Now try calling this function with a positive radius to make sure it works.\n",
|
||||||
|
"print(quadarea(2,3))\n",
|
||||||
|
"print(circle_area(2))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"ename": "ValueError",
|
||||||
|
"evalue": "Radius cannot be negative, you fool!",
|
||||||
|
"output_type": "error",
|
||||||
|
"traceback": [
|
||||||
|
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
|
||||||
|
"\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)",
|
||||||
|
"Cell \u001b[0;32mIn[15], line 3\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[38;5;66;03m# Now try calling this function with a negative radius.\u001b[39;00m\n\u001b[0;32m----> 3\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[43mcircle_area\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m-\u001b[39;49m\u001b[38;5;241;43m2\u001b[39;49m\u001b[43m)\u001b[49m)\n",
|
||||||
|
"Cell \u001b[0;32mIn[14], line 10\u001b[0m, in \u001b[0;36mcircle_area\u001b[0;34m(radius)\u001b[0m\n\u001b[1;32m 8\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mcircle_area\u001b[39m(radius):\n\u001b[1;32m 9\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m radius \u001b[38;5;241m<\u001b[39m \u001b[38;5;241m0\u001b[39m:\n\u001b[0;32m---> 10\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mRadius cannot be negative, you fool!\u001b[39m\u001b[38;5;124m'\u001b[39m)\n\u001b[1;32m 11\u001b[0m area \u001b[38;5;241m=\u001b[39m np\u001b[38;5;241m.\u001b[39mpi \u001b[38;5;241m*\u001b[39m (radius\u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39m\u001b[38;5;241m2\u001b[39m)\n\u001b[1;32m 12\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m area\n",
|
||||||
|
"\u001b[0;31mValueError\u001b[0m: Radius cannot be negative, you fool!"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Now try calling this function with a negative radius.\n",
|
||||||
|
"\n",
|
||||||
|
"print(circle_area(-2))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"The syntax for <b>raise</b> is the exception class (for instance, ValueError() if a value is forbidden; this is the most common type of exception you'll have, but we'll see others as we go) followed by user-defined text that will give you more information about the error.\n",
|
||||||
|
"\n",
|
||||||
|
"Luckily, Python also lets you build in ways to deal with common exceptions if you're pretty sure you know where the user went wrong. For example, they may have accidentally put a negative sign on the radius, but you're pretty sure they just meant the positive value. In that case, you can use a <b>try/except</b> block, which will attempt to resolve the error."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"28.274333882308138\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# As an example, this code will call the area() function, and if it gets\n",
|
||||||
|
"# a ValueError exception, it'll try again with the absolute value\n",
|
||||||
|
"# of the range.\n",
|
||||||
|
"\n",
|
||||||
|
"radius = -3\n",
|
||||||
|
"try:\n",
|
||||||
|
" a = circle_area(radius)\n",
|
||||||
|
"except ValueError:\n",
|
||||||
|
" a = circle_area(abs(radius))\n",
|
||||||
|
" \n",
|
||||||
|
"print(a)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>TAKE-HOME POINTS</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li>A <b>module</b> is a library of Python source code that gives access to new variables and functions.</li>\n",
|
||||||
|
" <li>Modules can be imported as whatever name you like.</li>\n",
|
||||||
|
" <li>A <b>raise</b> statement lets you define your own error conditions and stop code when they're met.</li>\n",
|
||||||
|
" <li>A <b>try/except</b> block will let you fix common issues that would otherwise result in exceptions.</li>\n",
|
||||||
|
"</ul>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# you can import modules with any name you want"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3 (ipykernel)",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python3"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 3
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython3",
|
||||||
|
"version": "3.11.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 4
|
||||||
|
}
|
||||||
487
python/atms-310/notebooks/Week 03 W.ipynb
Executable file
487
python/atms-310/notebooks/Week 03 W.ipynb
Executable file
@ -0,0 +1,487 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h1>6. Arrays</h1>\n",
|
||||||
|
"\n",
|
||||||
|
"<h2>10/11/2023</h2>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"tags": []
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"<h2>6.0 Last Time...</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li>A <b>module</b> is a library of Python source code that gives access to new variables and functions.</li>\n",
|
||||||
|
" <li>Modules can be imported as whatever name you like.</li>\n",
|
||||||
|
" <li>A <b>raise</b> statement lets you define your own error conditions and stop code when they're met.</li>\n",
|
||||||
|
" <li>A <b>try/except</b> block will let you fix common issues that would otherwise result in exceptions.</li>\n",
|
||||||
|
"</ul>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>6.1 Creating Arrays</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"An <b>array</b> is similar to a list, but has a lot of additional functionality! \n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li>all elements are of the same type (this speeds up operations)</li>\n",
|
||||||
|
" <li>multi-dimensional arrays clearly supported</li>\n",
|
||||||
|
" <li>array operations are supported (like matrix multiplication!)</li>\n",
|
||||||
|
"</ul>\n",
|
||||||
|
"\n",
|
||||||
|
"Using an array requires NumPy - remember to import it at the start of your code!\n",
|
||||||
|
"\n",
|
||||||
|
"The easiest way to create an array is to take a preexisting list and convert it into an array using NumPy's <b>array</b> function."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 2,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[[90, 123, 43], [123, 1432, 534]]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"import numpy as np\n",
|
||||||
|
"\n",
|
||||||
|
"# Start with a predefined list.\n",
|
||||||
|
"\n",
|
||||||
|
"mylist = [[90,123,43],[123,1432,534]]\n",
|
||||||
|
"print(mylist)\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 8,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[[ 90 123 43]\n",
|
||||||
|
" [ 123 1432 534]]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Now let's make this a 2D array:\n",
|
||||||
|
"\n",
|
||||||
|
"a = np.array(mylist)\n",
|
||||||
|
"\n",
|
||||||
|
"print(a)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>6.2 Initializing Arrays</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"Just like when we were building lists, sometimes you know the size and shape of the array you'd like to build, but not the individual contents.\n",
|
||||||
|
"\n",
|
||||||
|
"In those cases, you can create an array of zeroes where non-zero values will eventually be filled in."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 10,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[[0. 0.]\n",
|
||||||
|
" [0. 0.]\n",
|
||||||
|
" [0. 0.]]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Let's use the zeros() function to make a 3x2 array.\n",
|
||||||
|
"\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"\n",
|
||||||
|
"x = np.zeros((3,2))\n",
|
||||||
|
"print(x)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"One of the more important ways we used lists previously was with the range() function, which counted up from zero to one less than the integer in parentheses. NumPy has an equivalent array version to save time: arange()."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 4,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[0 1 2 3 4 5 6 7 8 9]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Use arange() to create an array of 10 elements\n",
|
||||||
|
"# that starts from 0 and counts up through 9.\n",
|
||||||
|
"\n",
|
||||||
|
"import numpy as np # recall you only have to import once!\n",
|
||||||
|
"\n",
|
||||||
|
"a = np.arange(10)\n",
|
||||||
|
"print(a)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 5,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Note that you can also have a float version of arange:\n",
|
||||||
|
"a = np.arange(10.0)\n",
|
||||||
|
"print(a)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>6.3 Array Indexing</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"Just like with lists, arrays start counting at 0, and you can use negative numbers to start counting backwards (e.g., -1 refers to the last element in the array).\n",
|
||||||
|
"\n",
|
||||||
|
"We can also slice arrays, which is a process very similar to slicing lists:\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li>The element numbers are separated by a colon.</li>\n",
|
||||||
|
" <li><b>Inclusive</b> lower limit, <b>exclusive</b> upper limit.</li>\n",
|
||||||
|
" <li>If one of the limits is omitted, the range is extended to the end of the range (so if the lower limit is omitted, the range extends to the very beginning of the array)</li>\n",
|
||||||
|
" <li>To specify all elements, use a colon by itself.</li>\n",
|
||||||
|
"</ul>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 6,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"3.2\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Let's create a 1D array.\n",
|
||||||
|
"\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"\n",
|
||||||
|
"a = np.array([2, 3.2, 5.5, -6.4, -2.2, 2.4])\n",
|
||||||
|
"\n",
|
||||||
|
"print(a[1])"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 7,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[ 3.2 5.5 -6.4]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"print(a[1:4])"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 9,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[2. 3.2 5.5]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"print(a[:3])"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 10,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[ 2. 3.2 5.5 -6.4 -2.2 2.4]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"print(a[:])"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"So far so good... but what about multidimensional arrays? In multidimensional arrays, indexing for each dimension is separated by commas. In a 2D array, the indexing is done by [row, col]."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 11,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[[ 2. 3.2 5.5 -6.4 -2.2 2.4]\n",
|
||||||
|
" [ 1. 22. 4. 0.1 5.3 -9. ]\n",
|
||||||
|
" [ 3. 1. 2.1 21. 1.1 -2. ]]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Let's create a 2D array.\n",
|
||||||
|
"\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"\n",
|
||||||
|
"# For the following, I've played around with the spacing\n",
|
||||||
|
"# a bit to make the dimensions more clear, but this is optional!\n",
|
||||||
|
"\n",
|
||||||
|
"a = np.array([[2,3.2,5.5,-6.4,-2.2,2.4],\n",
|
||||||
|
" [1, 22, 4, 0.1, 5.3, -9],\n",
|
||||||
|
" [3, 1,2.1, 21, 1.1, -2]])\n",
|
||||||
|
"\n",
|
||||||
|
"# This array has 3 rows and 6 columns.\n",
|
||||||
|
"# Note that Python knew this was all part of the same line\n",
|
||||||
|
"# even without using any special character to warn it.\n",
|
||||||
|
"\n",
|
||||||
|
"print(a)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<b>Let's try some examples!</b>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 12,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[-6.4 0.1 21. ]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Print the column with index 3 (the fourth column).\n",
|
||||||
|
"\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"\n",
|
||||||
|
"print(a[:,3])"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 13,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[ 1. 22. 4. 0.1 5.3 -9. ]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Print the row with index 1 (the second row).\n",
|
||||||
|
"\n",
|
||||||
|
"print(a[1,:])"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 14,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[22. 4. 0.1]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Write a print statement that prints the slice [22, 4, 0.1].\n",
|
||||||
|
"\n",
|
||||||
|
"# [row, column]\n",
|
||||||
|
"# \n",
|
||||||
|
"print(a[1,1:4])"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>6.4 Take-Home Points</h2>\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li>An array is NumPy's version of a list, which allows you to work with matrices.</li>\n",
|
||||||
|
" <li>All elements of an array are of the same type.</li>\n",
|
||||||
|
" <li>You can either create a new array or convert an existing list into one.</li>\n",
|
||||||
|
" <li>The zeros() function is useful for initializing an array when you know the shape and size but not the contents.</li>\n",
|
||||||
|
" <li>The arange() function serves a similar purpose to the range() function with lists.</li>\n",
|
||||||
|
" <li>Similar to lists, arrays can be sliced, but arrays can be sliced across each of their dimensions.</li>\n",
|
||||||
|
"</ul>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<b>Challenge Exercises:</b>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 2,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[[0. 0. 0. 0. 0.]\n",
|
||||||
|
" [0. 0. 0. 0. 0.]\n",
|
||||||
|
" [0. 0. 0. 0. 0.]\n",
|
||||||
|
" [0. 0. 0. 0. 0.]]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"#1. What is the code to create a 4-row, 5-column array of zeros and assign it to the variable a?\n",
|
||||||
|
"\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"\n",
|
||||||
|
"a = np.zeros((4,5))\n",
|
||||||
|
"print(a)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 3,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[4. 2.1]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"#2. Using array a from above, answer the following questions:\n",
|
||||||
|
"\n",
|
||||||
|
"a = np.array([[2,3.2,5.5,-6.4,-2.2,2.4],\n",
|
||||||
|
" [1, 22, 4, 0.1, 5.3, -9],\n",
|
||||||
|
" [3, 1,2.1, 21, 1.1, -2]])\n",
|
||||||
|
"\n",
|
||||||
|
"#a. What is a[:,3]?\n",
|
||||||
|
"\n",
|
||||||
|
"#[-6.4,0.1,21.]\n",
|
||||||
|
"#print(a[:,3])\n",
|
||||||
|
"\n",
|
||||||
|
"#b. What is a[1:4,0:2]?\n",
|
||||||
|
"#[1,22]\n",
|
||||||
|
"#[3,1,]\n",
|
||||||
|
"\n",
|
||||||
|
"# print(a[1:4,0:2])\n",
|
||||||
|
"\n",
|
||||||
|
"#c. What will b = a[1:,2] do?\n",
|
||||||
|
"\n",
|
||||||
|
"b = a[1:,2] # row 1 to the end, index 2\n",
|
||||||
|
"print(b)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3 (ipykernel)",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python3"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 3
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython3",
|
||||||
|
"version": "3.11.5"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 4
|
||||||
|
}
|
||||||
420
python/atms-310/notebooks/Week 04 F.ipynb
Executable file
420
python/atms-310/notebooks/Week 04 F.ipynb
Executable file
@ -0,0 +1,420 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h1>8. Text I/O</h1>\n",
|
||||||
|
"\n",
|
||||||
|
"<h2>10/20/2023</h2>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>8.0 Last Time...</h2>\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li>You can use functions within NumPy to find the shape, number of dimensions, and number of elements in any array.</li>\n",
|
||||||
|
" <li><b>numpy.where()</b> will let you find the locations of elements within an array that meet a specified criterion.</li>\n",
|
||||||
|
" <li>Some functions within NumPy allow you to manipulate arrays, such as reshaping, transposing, \"unraveling\", concatenation, and repeating individual array elements.</li>\n",
|
||||||
|
" <li>When you're in a situation with multiple nested loops, often you can instead perform all operations a lot more easily by using array syntax.</li>\n",
|
||||||
|
" <li>Mathematical operations act on arrays elementwise.</li>\n",
|
||||||
|
" <li>When testing within an array, <b>and</b> and <b>or</b> cannot be used; instead, use NumPy's built-in functions.</li>\n",
|
||||||
|
"</ul>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>8.1 File Objects</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"A file object is just a variable that represents the file within Python. The process of creating a file object is the same general idea as creating any variable: you create it by assignment.\n",
|
||||||
|
"\n",
|
||||||
|
"For a text file, you can create a file with the built-in <b>open()</b> statement. The first argument in <b>open</b> gives the filename, and the second sets the mod for the file:\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li><b>'r'</b>: sets the file to read-only.</li>\n",
|
||||||
|
" <li><b>'w'</b>: sets the file to writing mode.</li>\n",
|
||||||
|
" <li><b>'a'</b>: sets the file to append mode (you can only add new things to the end).</li>\n",
|
||||||
|
"</ul>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 2,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"data": {
|
||||||
|
"text/plain": [
|
||||||
|
"_io.TextIOWrapper"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"execution_count": 2,
|
||||||
|
"metadata": {},
|
||||||
|
"output_type": "execute_result"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Try opening the 'test.txt' file that you added to your server.\n",
|
||||||
|
"data = open(\"../test.txt\", \"r\")\n",
|
||||||
|
"type(data)\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"When you're done with a file, you can use the <b>close()</b> method."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 3,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Close that file back up.\n",
|
||||||
|
"data.close()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>8.2 Text Input/Output</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"To read a line from a file into a variable, you can use the <b>readline()</b> method."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 7,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"This is a test!\n",
|
||||||
|
"\n",
|
||||||
|
"Here's some information:\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# First, open the file.\n",
|
||||||
|
"data = open(\"../test.txt\",\"r\")\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# Assign the first line of text to the variable aline.\n",
|
||||||
|
"aline = data.readline()\n",
|
||||||
|
"\n",
|
||||||
|
"# Calling readline() multiple times in a row will print the next row.\n",
|
||||||
|
"bline = data.readline()\n",
|
||||||
|
"\n",
|
||||||
|
"# Print those first two lines of text.\n",
|
||||||
|
"print(aline)\n",
|
||||||
|
"print(bline)\n",
|
||||||
|
"\n",
|
||||||
|
"# Close the file. (This is good practice!)\n",
|
||||||
|
"data.close()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"You can also write a loop to go through the whole file!"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 11,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"This is a test!\n",
|
||||||
|
"\n",
|
||||||
|
"Here's some information:\n",
|
||||||
|
"\n",
|
||||||
|
"IMPORTANT THINGS TO KNOW\n",
|
||||||
|
"\n",
|
||||||
|
"Okay, that's all I got.\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"data = open(\"../test.txt\", \"r\")\n",
|
||||||
|
"\n",
|
||||||
|
"for i in data:\n",
|
||||||
|
" print(i)\n",
|
||||||
|
" \n",
|
||||||
|
"data.close()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Okay, but that's fairly limiting; more often, you'll want to read the whole file and put each line into a list as an element; this can be done using <b>readlines()</b> (note the plural!)."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 14,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"['This is a test!\\n', \"Here's some information:\\n\", 'IMPORTANT THINGS TO KNOW\\n', \"Okay, that's all I got.\"]\n",
|
||||||
|
"<class 'list'>\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Let's open the file again.\n",
|
||||||
|
"data = open(\"../test.txt\", \"r\")\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# Save the file's contents to a list.\n",
|
||||||
|
"contents = data.readlines()\n",
|
||||||
|
"\n",
|
||||||
|
"print(contents)\n",
|
||||||
|
"print(type(contents))\n",
|
||||||
|
"\n",
|
||||||
|
"# Close that file!\n",
|
||||||
|
"data.close()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Note that there's a newline (<b>\\n</b>) character at the end of each line (except the last one).\n",
|
||||||
|
"\n",
|
||||||
|
"To write to a file, you can use the <b>write()</b> method (obviously this doesn't work if a file is in read-only mode)."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Let's open a file in writing mode.\n",
|
||||||
|
"data = open(\"../test.txt\", \"w\")\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# Write a phrase to the file.\n",
|
||||||
|
"data.write(\"hello world\")\n",
|
||||||
|
"data.close()\n",
|
||||||
|
"\n",
|
||||||
|
"# i didnt run this, and dont ever run this. will overwrite file.\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Note that this overwrites everything currently inside the file! To write multiple lines (in list format) to a file, use <b>writelines()</b>."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 17,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"ename": "AttributeError",
|
||||||
|
"evalue": "'_io.TextIOWrapper' object has no attribute 'append'",
|
||||||
|
"output_type": "error",
|
||||||
|
"traceback": [
|
||||||
|
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
|
||||||
|
"\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)",
|
||||||
|
"\u001b[1;32m/Users/nik/data/python/notebooks/Week 04 F.ipynb Cell 16\u001b[0m line \u001b[0;36m7\n\u001b[1;32m <a href='vscode-notebook-cell:/Users/nik/data/python/notebooks/Week%2004%20F.ipynb#X21sZmlsZQ%3D%3D?line=4'>5</a>\u001b[0m data\u001b[39m.\u001b[39mwritelines(contents)\n\u001b[1;32m <a href='vscode-notebook-cell:/Users/nik/data/python/notebooks/Week%2004%20F.ipynb#X21sZmlsZQ%3D%3D?line=5'>6</a>\u001b[0m data \u001b[39m=\u001b[39m \u001b[39mopen\u001b[39m(\u001b[39m\"\u001b[39m\u001b[39m../test.txt\u001b[39m\u001b[39m\"\u001b[39m, \u001b[39m\"\u001b[39m\u001b[39ma\u001b[39m\u001b[39m\"\u001b[39m)\n\u001b[0;32m----> <a href='vscode-notebook-cell:/Users/nik/data/python/notebooks/Week%2004%20F.ipynb#X21sZmlsZQ%3D%3D?line=6'>7</a>\u001b[0m data\u001b[39m.\u001b[39;49mappend(\u001b[39m\"\u001b[39m\u001b[39mpoopy booty butt balls\u001b[39m\u001b[39m\"\u001b[39m)\n\u001b[1;32m <a href='vscode-notebook-cell:/Users/nik/data/python/notebooks/Week%2004%20F.ipynb#X21sZmlsZQ%3D%3D?line=7'>8</a>\u001b[0m data\u001b[39m.\u001b[39mclose()\n",
|
||||||
|
"\u001b[0;31mAttributeError\u001b[0m: '_io.TextIOWrapper' object has no attribute 'append'"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"data = open(\"../test.txt\", \"w\")\n",
|
||||||
|
"\n",
|
||||||
|
"# Earlier in this notebook we saved the contents of our file to a variable 'contents'.\n",
|
||||||
|
"\n",
|
||||||
|
"data.writelines(contents)\n",
|
||||||
|
"data = open(\"../test.txt\", \"a\")\n",
|
||||||
|
"data.(\"poopy booty butt balls\")\n",
|
||||||
|
"data.close()\n",
|
||||||
|
"\n",
|
||||||
|
"# ok whatever ill figure it out when i need to"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>8.3 Processing File Contents</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"As you might imagine, the contents of files can be pretty unwieldy. Luckily, there are a lot of methods that will make data easier to read!\n",
|
||||||
|
"\n",
|
||||||
|
"Sometimes (as with .csv files) you'll want to take a string and break it into list using a particular separator. <b>split()</b> is a useful tool!"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 19,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"['3.4', '2.1', '-2.6']\n",
|
||||||
|
"['3.4', '2.1', '-2.6']\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Let's create a single string that has three pieces of data in it.\n",
|
||||||
|
"a = '3.4 2.1 -2.6'\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# The obvious choice for a separator is a space.\n",
|
||||||
|
"print(a.split(\" \"))\n",
|
||||||
|
"a = '3.4,2.1,-2.6'\n",
|
||||||
|
"print(a.split(\",\"))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"If everything we read from a file is a string, we're sometimes going to have to convert to integers or floats."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 23,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"['3.4', '2.1', '-2.6']\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# We'll need NumPy for this!\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# Let's look at a typical situation: we've grabbed some numbers from a csv file.\n",
|
||||||
|
"a = '3.4,2.1,-2.6'\n",
|
||||||
|
"a = a.split(\",\")\n",
|
||||||
|
"\n",
|
||||||
|
"# Note that these are still strings.\n",
|
||||||
|
"print(a)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 25,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[ 3.4 2.1 -2.6]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# We can convert these to floats the way we did before!\n",
|
||||||
|
"b = np.zeros(len(a))\n",
|
||||||
|
"for i in range(len(a)):\n",
|
||||||
|
" b[i] = float(a[i])\n",
|
||||||
|
"print(b)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Alternatively, we can convert to an array and use the <b>astype()</b> function built-in there. <b>'d'</b> is a float (double-precision), <b>'l'</b> is an integer (long integer)."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 27,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[ 3.4 2.1 -2.6]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"bnum = np.array(a).astype(\"d\")\n",
|
||||||
|
"print(bnum)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>8.4 Take-Home Points</h2>\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li>The <b>open()</b> statement lets you open a file in read, write, or append mode.</li>\n",
|
||||||
|
" <li>Files should always be closed using the <b>close()</b> statement.</li>\n",
|
||||||
|
" <li>You can read a single line with <b>readline()</b>, and multiple lines with <b>readlines()</b>.</li>\n",
|
||||||
|
" <li>The <b>write()</b> method allows you to write a single line, and the <b>writelines()</b> method allows you to write multiple lines.</li>\n",
|
||||||
|
" <li><b>split()</b> lets you break strings based on defined separators.</li>\n",
|
||||||
|
"</ul>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# remember to close files\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3 (ipykernel)",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python3"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 3
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython3",
|
||||||
|
"version": "3.11.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 4
|
||||||
|
}
|
||||||
479
python/atms-310/notebooks/Week 05 F-1.ipynb
Executable file
479
python/atms-310/notebooks/Week 05 F-1.ipynb
Executable file
@ -0,0 +1,479 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h1>11. Introduction to Object-Oriented Programming</h1>\n",
|
||||||
|
"<h2>10/27/2023</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"<h2>11.0 Last Time...</h2>\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li>NetCDF is a powerful file type containing global attributes, variables, variable attributes, and dimensions.</li>\n",
|
||||||
|
" <li>We can read from NetCDF files using similar syntax to that for regular files.</li>\n",
|
||||||
|
" <li>Using attributes such as 'dimensions' and 'variables', we can learn about individual variables in the dataset.</li>\n",
|
||||||
|
" <li>We can also write to NetCDF files in a simlar way.</li>\n",
|
||||||
|
"</ul>\n",
|
||||||
|
"\n",
|
||||||
|
"<h2>11.1 What is Object-Oriented Programming?</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"OOP is presented here in opposition to procedural programming. <b>Procedural</b> programs consider two entities: data and functions. Procedurally, the two things are different: a function will take data as input and return data as output (this should sound familiar!). There's nothing customizable about a function with respect to data, which means you can use functions on various types of data with no restrictions... which can you get into trouble.\n",
|
||||||
|
"\n",
|
||||||
|
"In reality, though, we tend to think of things as having both \"state\" and \"behavior\". People can have a state (tall, short, etc.) but also a behavior (playing basketball, running, etc.), and the two can happen simultaneously.\n",
|
||||||
|
"\n",
|
||||||
|
"Object-oriented programming attempts to imitate this approach, so specific objects in the code will have a state and a behavior attached to them.\n",
|
||||||
|
"\n",
|
||||||
|
"<h2>11.2 What is an Object?</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"An object in programming has two entities attached to it: data... and the things that <i>act</i> on that data. The data are called <b>attributes</b>, and the functions attached to the object that can act on that data are called <b>methods</b>. \n",
|
||||||
|
"\n",
|
||||||
|
"These methods are specifically made to act on attributes; they aren't just random functions meant as one-size-fits-all solutions, which is what we would see in procedural programming.\n",
|
||||||
|
"\n",
|
||||||
|
"Objects are generally specific realizations of some <b>class</b> or <b>type</b>. As an example, individual people are specific realizations of the <b>class</b> of human beings. Specific realizations (instances) differ from each other in details but have the same overall pattern. In OOP, specific realizations are <b>instances</b> and common patterns are <b>classes</b>.\n",
|
||||||
|
"\n",
|
||||||
|
"<h2>11.3 How do Objects Work?</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"In Python, strings (like almost everything in Python) are objects. Built into Python, there is a class called 'strings', and each time you make a new string, you're using that definition. Python implicitly defines attributes and methods for all string objects; no matter what string you create, you have that set of data and functions associated with your string."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 3,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"data": {
|
||||||
|
"text/plain": [
|
||||||
|
"['__add__',\n",
|
||||||
|
" '__class__',\n",
|
||||||
|
" '__contains__',\n",
|
||||||
|
" '__delattr__',\n",
|
||||||
|
" '__dir__',\n",
|
||||||
|
" '__doc__',\n",
|
||||||
|
" '__eq__',\n",
|
||||||
|
" '__format__',\n",
|
||||||
|
" '__ge__',\n",
|
||||||
|
" '__getattribute__',\n",
|
||||||
|
" '__getitem__',\n",
|
||||||
|
" '__getnewargs__',\n",
|
||||||
|
" '__getstate__',\n",
|
||||||
|
" '__gt__',\n",
|
||||||
|
" '__hash__',\n",
|
||||||
|
" '__init__',\n",
|
||||||
|
" '__init_subclass__',\n",
|
||||||
|
" '__iter__',\n",
|
||||||
|
" '__le__',\n",
|
||||||
|
" '__len__',\n",
|
||||||
|
" '__lt__',\n",
|
||||||
|
" '__mod__',\n",
|
||||||
|
" '__mul__',\n",
|
||||||
|
" '__ne__',\n",
|
||||||
|
" '__new__',\n",
|
||||||
|
" '__reduce__',\n",
|
||||||
|
" '__reduce_ex__',\n",
|
||||||
|
" '__repr__',\n",
|
||||||
|
" '__rmod__',\n",
|
||||||
|
" '__rmul__',\n",
|
||||||
|
" '__setattr__',\n",
|
||||||
|
" '__sizeof__',\n",
|
||||||
|
" '__str__',\n",
|
||||||
|
" '__subclasshook__',\n",
|
||||||
|
" 'capitalize',\n",
|
||||||
|
" 'casefold',\n",
|
||||||
|
" 'center',\n",
|
||||||
|
" 'count',\n",
|
||||||
|
" 'encode',\n",
|
||||||
|
" 'endswith',\n",
|
||||||
|
" 'expandtabs',\n",
|
||||||
|
" 'find',\n",
|
||||||
|
" 'format',\n",
|
||||||
|
" 'format_map',\n",
|
||||||
|
" 'index',\n",
|
||||||
|
" 'isalnum',\n",
|
||||||
|
" 'isalpha',\n",
|
||||||
|
" 'isascii',\n",
|
||||||
|
" 'isdecimal',\n",
|
||||||
|
" 'isdigit',\n",
|
||||||
|
" 'isidentifier',\n",
|
||||||
|
" 'islower',\n",
|
||||||
|
" 'isnumeric',\n",
|
||||||
|
" 'isprintable',\n",
|
||||||
|
" 'isspace',\n",
|
||||||
|
" 'istitle',\n",
|
||||||
|
" 'isupper',\n",
|
||||||
|
" 'join',\n",
|
||||||
|
" 'ljust',\n",
|
||||||
|
" 'lower',\n",
|
||||||
|
" 'lstrip',\n",
|
||||||
|
" 'maketrans',\n",
|
||||||
|
" 'partition',\n",
|
||||||
|
" 'removeprefix',\n",
|
||||||
|
" 'removesuffix',\n",
|
||||||
|
" 'replace',\n",
|
||||||
|
" 'rfind',\n",
|
||||||
|
" 'rindex',\n",
|
||||||
|
" 'rjust',\n",
|
||||||
|
" 'rpartition',\n",
|
||||||
|
" 'rsplit',\n",
|
||||||
|
" 'rstrip',\n",
|
||||||
|
" 'split',\n",
|
||||||
|
" 'splitlines',\n",
|
||||||
|
" 'startswith',\n",
|
||||||
|
" 'strip',\n",
|
||||||
|
" 'swapcase',\n",
|
||||||
|
" 'title',\n",
|
||||||
|
" 'translate',\n",
|
||||||
|
" 'upper',\n",
|
||||||
|
" 'zfill']"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"execution_count": 3,
|
||||||
|
"metadata": {},
|
||||||
|
"output_type": "execute_result"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# The dir() command gives you a list of all the attributes and methods\n",
|
||||||
|
"# associated with a given object.\n",
|
||||||
|
"a = \"hello world\"\n",
|
||||||
|
"dir(a)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 6,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"Hello World\n",
|
||||||
|
"HELLO WORLD\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# To refer to an attribute or method of an instance,\n",
|
||||||
|
"# you just add a period after the object name and then put\n",
|
||||||
|
"# the attribute or method name.\n",
|
||||||
|
"print(a.title())\n",
|
||||||
|
"print(a.upper())\n",
|
||||||
|
"# Methods can produce a return value, act on attributes of the object in-place,\n",
|
||||||
|
"# or both!"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 9,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"True\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# isupper() will determine whether the object is in uppercase.\n",
|
||||||
|
"b = \"BALLS\"\n",
|
||||||
|
"print(b.isupper())\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 8,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"3\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# To count the instances of a particular character, you can use count()\n",
|
||||||
|
"print(a.count(\"l\"))\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"As another example, let's consider how objects work for arrays!\n",
|
||||||
|
"\n",
|
||||||
|
"Arrays have attributes and methods built in to them just like any other object."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 11,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[[ 0. 1. 2.]\n",
|
||||||
|
" [ 3. 4. 5.]\n",
|
||||||
|
" [ 6. 7. 8.]\n",
|
||||||
|
" [ 9. 10. 11.]]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"import numpy as np\n",
|
||||||
|
"a = np.arange(12.)\n",
|
||||||
|
"a = np.reshape(a,(4,3))\n",
|
||||||
|
"print(a)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 12,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"['T', '__abs__', '__add__', '__and__', '__array__', '__array_finalize__', '__array_function__', '__array_interface__', '__array_prepare__', '__array_priority__', '__array_struct__', '__array_ufunc__', '__array_wrap__', '__bool__', '__class__', '__class_getitem__', '__complex__', '__contains__', '__copy__', '__deepcopy__', '__delattr__', '__delitem__', '__dir__', '__divmod__', '__dlpack__', '__dlpack_device__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', '__iadd__', '__iand__', '__ifloordiv__', '__ilshift__', '__imatmul__', '__imod__', '__imul__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__ior__', '__ipow__', '__irshift__', '__isub__', '__iter__', '__itruediv__', '__ixor__', '__le__', '__len__', '__lshift__', '__lt__', '__matmul__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmatmul__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__setitem__', '__setstate__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__xor__', 'all', 'any', 'argmax', 'argmin', 'argpartition', 'argsort', 'astype', 'base', 'byteswap', 'choose', 'clip', 'compress', 'conj', 'conjugate', 'copy', 'ctypes', 'cumprod', 'cumsum', 'data', 'diagonal', 'dot', 'dtype', 'dump', 'dumps', 'fill', 'flags', 'flat', 'flatten', 'getfield', 'imag', 'item', 'itemset', 'itemsize', 'max', 'mean', 'min', 'nbytes', 'ndim', 'newbyteorder', 'nonzero', 'partition', 'prod', 'ptp', 'put', 'ravel', 'real', 'repeat', 'reshape', 'resize', 'round', 'searchsorted', 'setfield', 'setflags', 'shape', 'size', 'sort', 'squeeze', 'std', 'strides', 'sum', 'swapaxes', 'take', 'tobytes', 'tofile', 'tolist', 'tostring', 'trace', 'transpose', 'var', 'view']\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Now let's look at all the attributes and methods!\n",
|
||||||
|
"print(dir(a))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 13,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"(4, 3)\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Any attributes with two underscores probably shouldn't\n",
|
||||||
|
"# be messed with! This is how Python decides what to do when\n",
|
||||||
|
"# you type '*' or '/'.\n",
|
||||||
|
"\n",
|
||||||
|
"# Some of the other interesting methods include:\n",
|
||||||
|
"\n",
|
||||||
|
"print(np.shape(a))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 15,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"data": {
|
||||||
|
"text/plain": [
|
||||||
|
"array([ 0., 1., 3., 6., 10., 15., 21., 28., 36., 45., 55., 66.])"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"execution_count": 15,
|
||||||
|
"metadata": {},
|
||||||
|
"output_type": "execute_result"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"a.cumsum()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 16,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[[ 0. 3. 6. 9.]\n",
|
||||||
|
" [ 1. 4. 7. 10.]\n",
|
||||||
|
" [ 2. 5. 8. 11.]]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"print(a.T)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 17,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"data": {
|
||||||
|
"text/plain": [
|
||||||
|
"array([[ 0., 0., 0.],\n",
|
||||||
|
" [ 0., 0., 0.],\n",
|
||||||
|
" [10., 10., 10.],\n",
|
||||||
|
" [10., 10., 10.]])"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"execution_count": 17,
|
||||||
|
"metadata": {},
|
||||||
|
"output_type": "execute_result"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"a.round(-1)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 18,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"data": {
|
||||||
|
"text/plain": [
|
||||||
|
"array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11.])"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"execution_count": 18,
|
||||||
|
"metadata": {},
|
||||||
|
"output_type": "execute_result"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"a.ravel()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<b>Practice Exercises!</b>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 24,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"The rain in Spain.\n",
|
||||||
|
"THE RAIN IN SPAIN.\n",
|
||||||
|
"True\n",
|
||||||
|
"3\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"a = 'The rain in Spain.'\n",
|
||||||
|
"#1. Create a new string b that is a but all in uppercase.\n",
|
||||||
|
"b = a.upper()\n",
|
||||||
|
"#2. Is a changed when you create b?\n",
|
||||||
|
"print(a)\n",
|
||||||
|
"print(b)\n",
|
||||||
|
"# no?\n",
|
||||||
|
"#3. How would you test to see whether b is in uppercase? That is, how \n",
|
||||||
|
"# could you return a boolean that is True or False depending on whether \n",
|
||||||
|
"# b is uppercase?\n",
|
||||||
|
"print(b.isupper())\n",
|
||||||
|
"#4. How would you calculate the number of occurrences of the letter 'n' in a?\n",
|
||||||
|
"print(a.count(\"n\"))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<b>Round 2!</b>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 34,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[[2.3 8. 3.2]\n",
|
||||||
|
" [4.3 0.4 4.3]\n",
|
||||||
|
" [1.2 0.3 5.4]\n",
|
||||||
|
" [4.3 5.6 6.5]]\n",
|
||||||
|
"[2.3 8. 3.2 4.3 0.4 4.3 1.2 0.3 5.4 4.3 5.6 6.5]\n",
|
||||||
|
"[[2.3 8. 3.2 4.3 0.4 4.3]\n",
|
||||||
|
" [1.2 0.3 5.4 4.3 5.6 6.5]]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"#1. Create a 3 column, 4 row array named a. The array can have any numerical values\n",
|
||||||
|
"# you want, as long as all the elements are not all identical.\n",
|
||||||
|
"x = np.array([[2.3,4.3,1.2,4.3],[8.0,0.4,0.3,5.6],[3.2,4.3,5.4,6.5]])\n",
|
||||||
|
"x = x.T\n",
|
||||||
|
"print(x)\n",
|
||||||
|
"#2. Create an array b that is a copy of a but is 1-D, not 2-D.\n",
|
||||||
|
"b = np.ravel(x)\n",
|
||||||
|
"print(b)\n",
|
||||||
|
"#3. Turn b into a 6 column, 2 row array.\n",
|
||||||
|
"b = np.reshape(b,(2,6))\n",
|
||||||
|
"#4. Create an array c where you round all elements of b to 1 decimal place.\n",
|
||||||
|
"c = b.round(1)\n",
|
||||||
|
"print(c)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>11.4 Take-Home Points</h2>\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li><b>Objects</b> have attributes and methods associated with them that can be listed using <b>dir()</b>.</li>\n",
|
||||||
|
" <li>Methods for strings include <b>upper()</b>, <b>isupper()</b>, <b>count()</b>, <b>title()</b>, etc.</li>\n",
|
||||||
|
" <li>Methods for arrays include <b>reshape()</b>, <b>ravel()</b>, <b>round()</b>, etc.</li>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3 (ipykernel)",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python3"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 3
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython3",
|
||||||
|
"version": "3.11.6"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 4
|
||||||
|
}
|
||||||
328
python/atms-310/notebooks/Week 05 F-2.ipynb
Executable file
328
python/atms-310/notebooks/Week 05 F-2.ipynb
Executable file
@ -0,0 +1,328 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h1>12. Defining Classes And More...</h1>\n",
|
||||||
|
"<h2>10/27/2023</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"<h2>12.0 Last Time...</h2>\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li><b>Objects</b> have attributes and methods associated with them that can be listed using <b>dir()</b>.</li>\n",
|
||||||
|
" <li>Methods for strings include <b>upper()</b>, <b>isupper()</b>, <b>count()</b>, <b>title()</b>, etc.</li>\n",
|
||||||
|
" <li>Methods for arrays include <b>reshape()</b>, <b>ravel()</b>, <b>round()</b>, etc.</li>\n",
|
||||||
|
"</ul>\n",
|
||||||
|
"\n",
|
||||||
|
"<h2>12.1 Defining A Class: The Theory</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"We talked about how all objects are instances of a class. Using <b>dir()</b> in the previous lecture, we saw the list of attributes and methods for the <b>string</b> and <b>array</b> classes. But just as you sometimes want to create your own functions depending on your application, sometimes you want to create your own classes!\n",
|
||||||
|
"\n",
|
||||||
|
"This is going to get a little abstract, so bear with me while we go through this in text form - we'll soon be looking and writing plenty of our own examples! This is complex and a little hard to think about because we're actually messing with the way Python works at a more fundamental level rather than just applying it.\n",
|
||||||
|
"\n",
|
||||||
|
"Similar to the <b>def</b> statement for functions, creating a new class involves a <b>class</b> statement. The indented block after this class statement constitutes the definition of the class.\n",
|
||||||
|
"\n",
|
||||||
|
"Inside your definition, to make life easier, you just refer to the instance of the class as <b>self</b>. For example, if you want an attribute called <b>data</b>, within the class definition it will be called <b>self.data</b>.\n",
|
||||||
|
"\n",
|
||||||
|
"Methods are defined the same way we've been talking about functions: with a <b>def</b> statement. Each method will have a set of arguments, just the way functions normally do. The first argument in a method when defining a new class is generally going to just be the word <b>self</b>, which essentially means \"take everything we have thus far and make use of it in what follows\". This is an argument you won't have to type in when you're actually <i>using</i> the method; it's just for behind-the-scenes work.\n",
|
||||||
|
"\n",
|
||||||
|
"Typically, your first method will be called <b>\\_\\_init\\_\\_</b> (remember, the double-underscores indicate a fundamental method in a given class!). Every time you create an instance of your new class (for example, every time you create a string as an instance of the string class), this \\_\\_init\\_\\_ method will be called. \"Init\" stands for \"initialization\"; this is where you put any important information you'll need when creating a new instance of a class. \n",
|
||||||
|
"\n",
|
||||||
|
"Okay, this has been a lot. Let's see it in action!\n",
|
||||||
|
"\n",
|
||||||
|
"<h2>12.2 Defining A Class: The Code</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"Let's define a class that's called simply <b>Book</b>.\n",
|
||||||
|
"\n",
|
||||||
|
"If we have a bunch of information associated with a book (its author, publisher, title, etc.), we can store it as an instance of the class Book. Rather than having it be a string or a list or a dictionary, it will just be called a Book. We can then come up with some helpful methods that will define what we can do to Books.\n",
|
||||||
|
"\n",
|
||||||
|
"Let's start our class definition. We use the word <b>class</b>, followed by the name of our class (by convention, they're typically capitalized). We then put the word <b>object</b> in parentheses; this argument is a special object that just identifies this as a class that doesn't depend on other classes. For the purposes of this course, just remember: a class definition should have the argument <b>object</b>."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 24,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"class Book(object):\n",
|
||||||
|
" \n",
|
||||||
|
" # We'll start by defining the method __init__.\n",
|
||||||
|
" # Its arguments are self, the Author's last and first names, the\n",
|
||||||
|
" # title, the place, the publisher, and the year.\n",
|
||||||
|
" def __init__(self, authlast, authfirst, title, place, publisher, year):\n",
|
||||||
|
" \n",
|
||||||
|
" \n",
|
||||||
|
" # We then set the convention for the rest of our class definition:\n",
|
||||||
|
" # the name of the object, followed by a dot, followed by\n",
|
||||||
|
" # the names of our various arguments.\n",
|
||||||
|
" self.authlast = authlast\n",
|
||||||
|
" self.authfirst = authfirst\n",
|
||||||
|
" self.title = title\n",
|
||||||
|
" self.place = place\n",
|
||||||
|
" self.publisher = publisher\n",
|
||||||
|
" self.year = year\n",
|
||||||
|
" \n",
|
||||||
|
" # Let's create a second method that will write a bibliography entry.\n",
|
||||||
|
" def write_bib_entry(self):\n",
|
||||||
|
" \n",
|
||||||
|
" # We won't need any additional arguments here, since it's all handled above.\n",
|
||||||
|
" return self.authlast + ',' + self.authfirst + ',' + self.title + ',' + self.place + ',' + self.publisher + ',' + self.year \n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
" # We could create intermediate steps here, but let's just return the final answer.\n",
|
||||||
|
" # def make_authoryear(self):\n",
|
||||||
|
" # return self.authoryear + ' (' + self.year + ')'\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Now that we have created our new class (<b>Book</b>), we can try creating some instances of the class!"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 19,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"<__main__.Book object at 0x10dd78110>\n",
|
||||||
|
"the evidential power of booty\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"booty = Book(\"Dubious\", \"Thomas\", \"the evidential power of booty\", \"sanfran\", \"lava press\", \"1999\")\n",
|
||||||
|
"print(booty)\n",
|
||||||
|
"print(booty.title)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 20,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"2003\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"data": {
|
||||||
|
"text/plain": [
|
||||||
|
"['__class__',\n",
|
||||||
|
" '__delattr__',\n",
|
||||||
|
" '__dict__',\n",
|
||||||
|
" '__dir__',\n",
|
||||||
|
" '__doc__',\n",
|
||||||
|
" '__eq__',\n",
|
||||||
|
" '__format__',\n",
|
||||||
|
" '__ge__',\n",
|
||||||
|
" '__getattribute__',\n",
|
||||||
|
" '__getstate__',\n",
|
||||||
|
" '__gt__',\n",
|
||||||
|
" '__hash__',\n",
|
||||||
|
" '__init__',\n",
|
||||||
|
" '__init_subclass__',\n",
|
||||||
|
" '__le__',\n",
|
||||||
|
" '__lt__',\n",
|
||||||
|
" '__module__',\n",
|
||||||
|
" '__ne__',\n",
|
||||||
|
" '__new__',\n",
|
||||||
|
" '__reduce__',\n",
|
||||||
|
" '__reduce_ex__',\n",
|
||||||
|
" '__repr__',\n",
|
||||||
|
" '__setattr__',\n",
|
||||||
|
" '__sizeof__',\n",
|
||||||
|
" '__str__',\n",
|
||||||
|
" '__subclasshook__',\n",
|
||||||
|
" '__weakref__',\n",
|
||||||
|
" 'authfirst',\n",
|
||||||
|
" 'authlast',\n",
|
||||||
|
" 'place',\n",
|
||||||
|
" 'publisher',\n",
|
||||||
|
" 'title',\n",
|
||||||
|
" 'write_bib_entry',\n",
|
||||||
|
" 'year']"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"execution_count": 20,
|
||||||
|
"metadata": {},
|
||||||
|
"output_type": "execute_result"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"butt = Book(\"martelli\",\"alex\",\"py in nutshell\",\"place in CA\", \"autoparts\",\"2003\")\n",
|
||||||
|
"print(butt.year)\n",
|
||||||
|
"dir(butt)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"That's pretty useful! Let's do a few exercises...\n",
|
||||||
|
"\n",
|
||||||
|
"<h2>12.3 Book Class Exercises</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"After running the code above, answer the following questions:\n",
|
||||||
|
"\n",
|
||||||
|
"<b>1. How would you print out the authorfirst attribute of the pynut instance?</b>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 21,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"Thomas\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"print(booty.authfirst)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<b>2. How would you print the full bibliography entry for the beauty instance?</b>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 22,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"Dubious,Thomas,the evidential power of booty,sanfran,lava press,1999\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"print(booty.write_bib_entry())"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<b>3. How would you change the publication year for the beauty instance to \"2010\"?</b>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 11,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"2010\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"booty.year = \"2010\"\n",
|
||||||
|
"print(booty.year)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>12.4 Further Class Exercises</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"<b>1. Create another instance of the Book class using a book of your choosing (or get creative and make something up!). Check to make sure it looks okay using the write_bib_entry() method.</b>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 23,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"butt,booty,balls,leftcheek,rightcheek,9090\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"ass = Book(\"butt\", \"booty\", \"balls\", \"leftcheek\", \"rightcheek\", \"9090\")\n",
|
||||||
|
"print(ass.write_bib_entry())"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<b>2. Add a method called make_authoryear to the class definition. This method will create an attribute called authoryear and will set it to a string composed of the author's name followed by the year of publication in parentheses: </b>Dubay (1999)<b>, for instance. This method should not have a return statement, but should instead use a line starting with </b>self.authoryear = <b>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>12.5 Take-Home Points</h2>\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li>A class can be created using a <b>class</b> statement followed by the name of the class.</li>\n",
|
||||||
|
" <li>Methods within a class definition are created using a <b>def</b> statement.</li>\n",
|
||||||
|
" <li><b>__init__</b> is typically the first method defined and is used to initialize the core features of the class.</li>\n",
|
||||||
|
"</ul>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3 (ipykernel)",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python3"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 3
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython3",
|
||||||
|
"version": "3.11.6"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 4
|
||||||
|
}
|
||||||
455
python/atms-310/notebooks/Week 05 M.ipynb
Executable file
455
python/atms-310/notebooks/Week 05 M.ipynb
Executable file
@ -0,0 +1,455 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h1>9. Data Analysis Exercise</h1>\n",
|
||||||
|
"<h2>10/23/2023</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"<h2>9.0 Last Time...</h2>\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li>The <b>open()</b> statement lets you open a file in read, write, or append mode.</li>\n",
|
||||||
|
" <li>Files should always be closed using the <b>close()</b> statement.</li>\n",
|
||||||
|
" <li>You can read a single line with <b>readline()</b>, and multiple lines with <b>readlines()</b>.</li>\n",
|
||||||
|
" <li>The <b>write()</b> method allows you to write a single line, and the <b>writelines()</b> method allows you to write multiple lines.</li>\n",
|
||||||
|
" <li><b>split()</b> lets you break strings based on defined separators.</li>\n",
|
||||||
|
"</ul>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>9.1 The General Idea...</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"Today we're going to be working our way through various ways of analyzing datasets. The datasets in question are called <b>data0001.txt</b>, <b>data0002.txt</b>, and <b>data0003.txt</b>.\n",
|
||||||
|
"\n",
|
||||||
|
"These datasets are just composed of randomly generated numbers that have particular statistical features. We're going to make use of file I/O techniques to calculate certain statistics for each of them.\n",
|
||||||
|
"\n",
|
||||||
|
"<h3>9.1.1 A Quick Review of Statistics</h3>\n",
|
||||||
|
"\n",
|
||||||
|
"As a review, the <b>mean</b> is what we typically think of as \"average\": the sum of all elements, divided by the total number of elements. A mean is a useful summary, but it is <b>sensitive to outliers</b>. As an example, consider the following:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 1,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"3.0\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"import numpy as np\n",
|
||||||
|
"a = np.array([1,2,3,4,5])\n",
|
||||||
|
"print(np.mean(a))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 2,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"31113.0\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Now consider an outlier: a value that's much higher or lower than the others.\n",
|
||||||
|
"a = np.array([1,2,3,4,155555])\n",
|
||||||
|
"print(np.mean(a))\n",
|
||||||
|
"# the mean is not resistant to outliers\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"If we suspect there are outliers in the data, we can instead use the <b>median</b>, which is not sensitive to outliers. The median simply organizes all the values in ascending order and picks the middle one (or averages the middle two). The median is said to be <b>resistant to outliers</b>."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 4,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"3.0\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"a = np.array([1,2,3,4,55555])\n",
|
||||||
|
"print(np.median(a))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Finding the mean or median of a dataset is only part of the story: we're often also interested in how spread out the data are. Consider the following examples:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 5,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"22221.000022501237\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"print(np.std(a))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"The arrays have the same mean (and the same median, actually), but the spread of values is very different. As a result, we use measures of spread such as the <b>standard deviation</b>, which is essentially a measure of the average distance between each value and the mean."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"So we can tell that the second array is more spread out than the first.\n",
|
||||||
|
"\n",
|
||||||
|
"Okay, but how does the standard deviation do when it comes to outliers?"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"There's a big difference there! So just like how the median can be used as a statistic instead of the mean when we suspect there are outliers, we can also use an outlier-resistant measure of spread called the <b>inter-quartile range (IQR)</b>.\n",
|
||||||
|
"\n",
|
||||||
|
"After sorting the data in ascending order, a <b>quartile</b> corresponds to a quarter of the data. Counting upward through the data, once we've reached 1/4 of the data, we've reached the first quartile. The second quartile is when we've reached 1/2 of the data (so the <b>second quartile is equal to the median</b>). The third quartile is when we've reached 3/4 of the data.\n",
|
||||||
|
"\n",
|
||||||
|
"The interquartile range is simply the difference between the 3rd quartile and the 1st quartile. This function isn't in NumPy (yet!), but it is in scipy.stats."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 6,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"3.0\n",
|
||||||
|
"3.0\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"import scipy.stats as S\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"\n",
|
||||||
|
"a = np.array([1,2,3,4,5,6,7])\n",
|
||||||
|
"b = np.array([1,2,3,4,5,6,1552345])\n",
|
||||||
|
"\n",
|
||||||
|
"print(S.iqr(a))\n",
|
||||||
|
"print(S.iqr(b))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"If you want to get fancy with your analysis, there's also <b>skewness</b> and <b>kurtosis</b>, but they're harder to puzzle out by hand.\n",
|
||||||
|
"\n",
|
||||||
|
"<b>Skewness</b> is a measure of how asymmetrical your distribution is: negative skew means a plot of the data has a longer left tail, whereas positive skew means a plot of the data has a longer right tail.\n",
|
||||||
|
"\n",
|
||||||
|
"<b>Kurtosis</b> is a measure of how sharp the peak is in a distribution, as compared to a Gaussian (bell-curve). If the kurtosis is greater than 3, it's got a sharper curve than a Gaussian distribution. If it's less than 3, it's got a more gradual curve than a Gaussian distribution.\n",
|
||||||
|
"\n",
|
||||||
|
"These are more complicated statistics, but you may come across the names, and they can come in handy when you're doing data analysis!"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 7,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"0.0\n",
|
||||||
|
"2.0412414522829976\n",
|
||||||
|
"-1.25\n",
|
||||||
|
"2.1666666665875907\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"print(S.skew(a))\n",
|
||||||
|
"print(S.skew(b))\n",
|
||||||
|
"\n",
|
||||||
|
"print(S.kurtosis(a))\n",
|
||||||
|
"print(S.kurtosis(b))\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>9.2 A Traditional Approach</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"We're going to call this a traditional approach because it's the sort of thing you could do in just about any programming language; it doesn't really take advantage of the power of Python.\n",
|
||||||
|
"\n",
|
||||||
|
"Our goal is to calculate the mean, median, standard deviation, IQR, skewness, and kurtosis of each of the 3 datasets!"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Start by importing the relevant packages.\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"import scipy.stats as s\n",
|
||||||
|
"\n",
|
||||||
|
"# Let's create a function that will read data from any file.\n",
|
||||||
|
"# The function has one argument: the name of the file.\n",
|
||||||
|
"def read(file):\n",
|
||||||
|
" fileobj = open(file, \"r\")\n",
|
||||||
|
" # Start by defining a file object. We're opening in read-only mode.\n",
|
||||||
|
" outputstr = fileobj.readlines()\n",
|
||||||
|
" # Next, use readlines() to create a variable containing all the data.\n",
|
||||||
|
" fileobj.close()\n",
|
||||||
|
" # Close the file!\n",
|
||||||
|
" outputarray = np.zeros(len(outputstr))\n",
|
||||||
|
" # Let's initalize an array that will contain all the individual values from the file.\n",
|
||||||
|
" for n in np.arange(len(outputstr)):\n",
|
||||||
|
" outputarray[i] = float(outputstr[i]) \n",
|
||||||
|
" # Finally, let's loop over all the lines and put their values into this new array.\n",
|
||||||
|
" return outputarray\n",
|
||||||
|
" # We now have a function that takes in a file name and puts\n",
|
||||||
|
" # all the data into an array!\n",
|
||||||
|
" # The final step is to return the data array.\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# Okay, so let's make use of this function for our three datasets.\n",
|
||||||
|
"data1 = read(\"../datasets/data001.txt\")\n",
|
||||||
|
"data2 = read(\"../datasets/data002.txt\")\n",
|
||||||
|
"data3 = read(\"../datasets/data003.txt\")\n",
|
||||||
|
"\n",
|
||||||
|
"# Calculate the stats!\n",
|
||||||
|
"mean1 = np.mean(data1)\n",
|
||||||
|
"mean1 = np.mean(data1)\n",
|
||||||
|
"mean1 = np.mean(data1)\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# Printing:\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>9.3 Array Storage</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"We can do better than that! Let's make use of arrays for the results."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Import the necessary packages.\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"import scipy.stats as s\n",
|
||||||
|
"\n",
|
||||||
|
"# Let's initialize arrays of our final values!\n",
|
||||||
|
"numfiles = 3\n",
|
||||||
|
"mean = np.zeros(numfiles)\n",
|
||||||
|
"median = np.zeros(numfiles)\n",
|
||||||
|
"std = np.zeros(numfiles)\n",
|
||||||
|
"\n",
|
||||||
|
"# Now, let's use a loop to calculate the values!\n",
|
||||||
|
" # We can use the index from the loop to name each file!\n",
|
||||||
|
"\n",
|
||||||
|
" # Now, just use readdata() to grab all the data from the file.\n",
|
||||||
|
"\n",
|
||||||
|
" # Calculate your statistics!\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# Once the loop is complete, print out the arrays.\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"That worked fairly well, but the big concern here is that sometimes your files won't be as nicely numbered as they are.\n",
|
||||||
|
"\n",
|
||||||
|
"<h2>9.4 Dictionary Storage</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"How can we use dictionaries to our advantage? This might solve our problem with our filenames! Instead of relying on them to be a perfectly numbered list, we can use them as keys in a dictionary.\n",
|
||||||
|
"\n",
|
||||||
|
"And there's a new import command we can use that will grab all the file names!"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# The usual suspects.\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"import scipy.stats as s\n",
|
||||||
|
"# And a new friend!\n",
|
||||||
|
"import glob\n",
|
||||||
|
"\n",
|
||||||
|
"# Let's start by getting a list of files in the directory.\n",
|
||||||
|
"# We don't want to grab EVERYTHING, so we'll say it has to start with the word 'data' and end with '.txt.'\n",
|
||||||
|
"filelist = glob.glob(\"../datasets/data*.txt\")\n",
|
||||||
|
"filelist.sort()\n",
|
||||||
|
"\n",
|
||||||
|
"# Now initialize our dictionaries as empty to begin with.\n",
|
||||||
|
"mean = {}\n",
|
||||||
|
"median = {}\n",
|
||||||
|
"stddev = {}\n",
|
||||||
|
"iqr = {}\n",
|
||||||
|
"skewness = {}\n",
|
||||||
|
"kurtosis = {}\n",
|
||||||
|
"\n",
|
||||||
|
"# Loop through all files.\n",
|
||||||
|
"for i in filelist:\n",
|
||||||
|
" # Read the data.\n",
|
||||||
|
" data = read(i)\n",
|
||||||
|
" # Assign key-value pairs!\n",
|
||||||
|
" \n",
|
||||||
|
" \n",
|
||||||
|
"# And, outside the loop, print the results.\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>9.5 MORE Dictionary Storage</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"Okay, well, what if we didn't want to have to make a separate dictionary for every statistical metric? Remember, the key:value pairs in dictionaries are very flexible and actually allow you to put dictionaries themselves into the values!"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Old friends, back again.\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# First, create a dictionary of metrics with the commands you'll need to calculate them.\n",
|
||||||
|
"\n",
|
||||||
|
"# And we get our files the usual way.\n",
|
||||||
|
"\n",
|
||||||
|
"# Now let's initialize a results dictionary for each metric.\n",
|
||||||
|
"\n",
|
||||||
|
"# Now loop through all files, storing the relevant metrics!\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"The power of what Python's enabled us to do here is that we can change almost anything very easily: adding or removing files, adding or removing metrics, it's all done with one or two lines of code at most. The first version we saw would have been <b>much</b> more complicated!"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>9.6 Take-Home Points</h2>\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li>Statistics that are not resistant to outliers include the mean, the standard deviation, skewness, and kurtosis.</li>\n",
|
||||||
|
" <li>Statistics that are resistant to outliers include the median and the interquartile range.</li>\n",
|
||||||
|
" <li>By making use of dictionaries, we can create versatile, non-hard-coded programs!</li>\n",
|
||||||
|
" <li>glob is a package that enables us to grab all files within a directory</li>\n",
|
||||||
|
"</ul>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3 (ipykernel)",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python3"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 3
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython3",
|
||||||
|
"version": "3.11.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 4
|
||||||
|
}
|
||||||
685
python/atms-310/notebooks/Week 05 W.ipynb
Executable file
685
python/atms-310/notebooks/Week 05 W.ipynb
Executable file
@ -0,0 +1,685 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h1>10. NetCDF I/O</h1>\n",
|
||||||
|
"<h2>10/25/2023</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"<h2>10.0 Last Time...</h2>\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li>Statistics that are not resistant to outliers include the mean, the standard deviation, skewness, and kurtosis.</li>\n",
|
||||||
|
" <li>Statistics that are resistant to outliers include the median and the interquartile range.</li>\n",
|
||||||
|
" <li>By making use of dictionaries, we can create versatile, non-hard-coded programs!</li>\n",
|
||||||
|
" <li>glob is a package that enables us to grab all files within a directory</li>\n",
|
||||||
|
"</ul>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>10.1 Structure of a NetCDF File</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"NetCDF is a commonly used file format in our field because it enables the storage of data as well as the storage of its <b>metadata</b>. Every major language in our field is equipped to deal with NetCDF files, and Python is no exception!\n",
|
||||||
|
"\n",
|
||||||
|
"There are <b>four</b> parameter types in a netCDF file:\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li><b>Global attributes:</b> strings that describe the file as a whole: for example, a title, who created it, what standards it follows.</li>\n",
|
||||||
|
" <li><b>Variables:</b> entities that hold data, which includes the data, the domain the data is defined on (dimensionality), and metadata about the data (for example, units).</li>\n",
|
||||||
|
" <li><b>Variable attributes:</b> actual storage of the data's metadata.</li>\n",
|
||||||
|
" <li><b>Dimensions:</b> not only define the domain, but also might have values of their own (for example, latitude values, longitude values, altitude values, etc.).</li>\n",
|
||||||
|
"</ul>\n",
|
||||||
|
"\n",
|
||||||
|
"As an example, you might have a timeseries of surface temperature for a latitude-longitude grid. The dimensions for that dataset would be <b>lat</b>, <b>lon</b>, and <b>time</b>. The variable <b>lat</b> would just tell you the number of elements in the <b>lat</b> dimension</b>; likewise for <b>lon</b> and <b>time</b>. Finally, you might have a variable containing temperatures called <b>Ts</b> that would be 3-D, with dimensions of <b>lat</b>, <b>lon</b>, and <b>time</b>.\n",
|
||||||
|
"\n",
|
||||||
|
"There are several packages that can read NetCDF files; we're going to learn SciPy today - it's not necessarily the best, but it is one of the easiest to learn, and SciPy is a useful package for many other reasons."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>10.2 Reading a NetCDF File</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"For NetCDF files, we're interested in the I/O functionality of SciPy, so we'll call that part of the package and assign it to an alias."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 2,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Import the I/O functionality of SciPy.\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"import scipy.io as S\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"To create a file object, it's actually a pretty similar approach to what we did in our I/O lecture."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 4,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"<scipy.io._netcdf.netcdf_file object at 0x7f1a0448e4d0>\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Read in the provided NetCDF file in read-only mode.\n",
|
||||||
|
"fileobj = S.netcdf_file(\"../datasets/air.mon.mean.nc\", mode=\"r\")\n",
|
||||||
|
"print(fileobj)\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"NetCDF file objects have several <b>attributes</b> that we can call on (more on this when we explore object-oriented programming). One of those attributes is called <b>variables</b>, which is a dictionary. The keys of the dictionary are strings corresponding to the names of the variables, and the values are a special kind of object called <b>variable objects</b> that contain the variable's values as well as any metadata (units, etc.).\n",
|
||||||
|
"\n",
|
||||||
|
"Another NetCDF file object attribute is <b>dimensions</b>, which is another dictionary. The keys of this dictionary are strings that are the names of the dimensions, and the values are the lengths of the dimensions.\n",
|
||||||
|
"\n",
|
||||||
|
"Let's see an example from our .nc file: a grid of monthly-mean temperature values."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 5,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"b'Monthly mean air temperature NCEP Reanalysis'\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Let's import NumPy and SciPy's I/O functionality.\n",
|
||||||
|
"fileobj = S.netcdf_file(\"../datasets/air.mon.mean.nc\", mode=\"r\")\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# Now, create a file object!\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# First, let's find out what information's in the title.\n",
|
||||||
|
"print(fileobj.title)\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 6,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"{'lon': 144, 'lat': 73, 'time': None}\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Now let's explore the dimensions dictionary.\n",
|
||||||
|
"print(fileobj.dimensions)\n",
|
||||||
|
"\n",
|
||||||
|
"# Time is set to 'None' because that's this file's\n",
|
||||||
|
"# 'unlimited' dimension; you can keep adding new times to it\n",
|
||||||
|
"# and it will use the same lat/lon grid."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 7,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"{'lat': <scipy.io._netcdf.netcdf_variable object at 0x7f19fffc28d0>, 'lon': <scipy.io._netcdf.netcdf_variable object at 0x7f19fffc3450>, 'time': <scipy.io._netcdf.netcdf_variable object at 0x7f19fffc1f50>, 'air': <scipy.io._netcdf.netcdf_variable object at 0x7f19fffc1bd0>}\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# And let's see what kinds of variables are inside.\n",
|
||||||
|
"print(fileobj.variables)\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 9,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"<scipy.io._netcdf.netcdf_variable object at 0x7f19fffc1bd0>\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Okay, that's all very messy!\n",
|
||||||
|
"# Now it's time to grab the values of air temperature.\n",
|
||||||
|
"\n",
|
||||||
|
"temp = fileobj.variables[\"air\"]\n",
|
||||||
|
"print(temp)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 10,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"b'degC'\n",
|
||||||
|
"(755, 73, 144)\n",
|
||||||
|
"[[[-34.926773 -34.926773 -34.926773 ... -34.926773 -34.926773\n",
|
||||||
|
" -34.926773 ]\n",
|
||||||
|
" [-35.13935 -35.129673 -35.12742 ... -35.188705 -35.170002\n",
|
||||||
|
" -35.14935 ]\n",
|
||||||
|
" [-34.352573 -34.04226 -33.768707 ... -35.333866 -35.002903\n",
|
||||||
|
" -34.671288 ]\n",
|
||||||
|
" ...\n",
|
||||||
|
" [-16.525156 -16.404509 -16.284832 ... -16.795155 -16.737736\n",
|
||||||
|
" -16.643543 ]\n",
|
||||||
|
" [-16.190313 -16.202248 -16.21677 ... -16.132574 -16.161928\n",
|
||||||
|
" -16.178377 ]\n",
|
||||||
|
" [-17.697733 -17.697733 -17.697733 ... -17.697733 -17.697733\n",
|
||||||
|
" -17.697733 ]]\n",
|
||||||
|
"\n",
|
||||||
|
" [[-33.311375 -33.311375 -33.311375 ... -33.311375 -33.311375\n",
|
||||||
|
" -33.311375 ]\n",
|
||||||
|
" [-34.65034 -34.476204 -34.29689 ... -35.18448 -35.009308\n",
|
||||||
|
" -34.835514 ]\n",
|
||||||
|
" [-34.1031 -33.619995 -33.161373 ... -35.606552 -35.103443\n",
|
||||||
|
" -34.602757 ]\n",
|
||||||
|
" ...\n",
|
||||||
|
" [-34.338963 -34.21862 -34.08241 ... -34.359997 -34.42724\n",
|
||||||
|
" -34.418617 ]\n",
|
||||||
|
" [-33.795513 -33.896553 -33.977238 ... -33.41517 -33.56758\n",
|
||||||
|
" -33.690342 ]\n",
|
||||||
|
" [-32.942413 -32.942413 -32.942413 ... -32.942413 -32.942413\n",
|
||||||
|
" -32.942413 ]]\n",
|
||||||
|
"\n",
|
||||||
|
" [[-29.716127 -29.716127 -29.716127 ... -29.716127 -29.716127\n",
|
||||||
|
" -29.716127 ]\n",
|
||||||
|
" [-29.4471 -29.499353 -29.551613 ... -29.365162 -29.385166\n",
|
||||||
|
" -29.41258 ]\n",
|
||||||
|
" [-28.544516 -28.366776 -28.227749 ... -29.282906 -29.01323\n",
|
||||||
|
" -28.763546 ]\n",
|
||||||
|
" ...\n",
|
||||||
|
" [-51.964516 -52.206455 -52.362263 ... -50.628704 -51.18032\n",
|
||||||
|
" -51.631298 ]\n",
|
||||||
|
" [-52.846123 -53.07613 -53.290974 ... -52.069355 -52.344517\n",
|
||||||
|
" -52.60097 ]\n",
|
||||||
|
" [-54.835476 -54.835476 -54.835476 ... -54.835476 -54.835476\n",
|
||||||
|
" -54.835476 ]]\n",
|
||||||
|
"\n",
|
||||||
|
" ...\n",
|
||||||
|
"\n",
|
||||||
|
" [[ -6.84033 -6.84033 -6.84033 ... -6.84033 -6.84033\n",
|
||||||
|
" -6.84033 ]\n",
|
||||||
|
" [ -8.222664 -8.076328 -7.9316626 ... -8.658329 -8.517663\n",
|
||||||
|
" -8.366997 ]\n",
|
||||||
|
" [ -8.124661 -7.610333 -7.1173277 ... -9.681327 -9.180997\n",
|
||||||
|
" -8.653992 ]\n",
|
||||||
|
" ...\n",
|
||||||
|
" [-54.956 -55.16667 -55.29166 ... -53.67867 -54.22433\n",
|
||||||
|
" -54.649338 ]\n",
|
||||||
|
" [-55.466324 -55.73534 -55.975994 ... -54.453335 -54.82867\n",
|
||||||
|
" -55.16467 ]\n",
|
||||||
|
" [-53.225002 -53.225002 -53.225002 ... -53.225002 -53.225002\n",
|
||||||
|
" -53.225002 ]]\n",
|
||||||
|
"\n",
|
||||||
|
" [[-16.640314 -16.640314 -16.640314 ... -16.640314 -16.640314\n",
|
||||||
|
" -16.640314 ]\n",
|
||||||
|
" [-20.58 -20.478704 -20.383224 ... -20.846767 -20.765804\n",
|
||||||
|
" -20.679348 ]\n",
|
||||||
|
" [-21.077736 -20.571283 -20.056448 ... -22.434835 -22.024187\n",
|
||||||
|
" -21.567738 ]\n",
|
||||||
|
" ...\n",
|
||||||
|
" [-44.52612 -44.629353 -44.69258 ... -43.85613 -44.15871\n",
|
||||||
|
" -44.375164 ]\n",
|
||||||
|
" [-44.219357 -44.39742 -44.56355 ... -43.50774 -43.770008\n",
|
||||||
|
" -44.004192 ]\n",
|
||||||
|
" [-41.401936 -41.401936 -41.401936 ... -41.401936 -41.401936\n",
|
||||||
|
" -41.401936 ]]\n",
|
||||||
|
"\n",
|
||||||
|
" [[-26.217333 -26.217333 -26.217333 ... -26.217333 -26.217333\n",
|
||||||
|
" -26.217333 ]\n",
|
||||||
|
" [-30.25533 -30.281328 -30.300997 ... -30.091661 -30.157658\n",
|
||||||
|
" -30.210995 ]\n",
|
||||||
|
" [-31.590332 -31.514662 -31.380667 ... -31.483662 -31.579662\n",
|
||||||
|
" -31.618664 ]\n",
|
||||||
|
" ...\n",
|
||||||
|
" [-32.93566 -32.809 -32.665333 ... -33.02433 -33.059994\n",
|
||||||
|
" -33.024666 ]\n",
|
||||||
|
" [-34.10533 -34.120663 -34.118332 ... -33.930668 -34.01266\n",
|
||||||
|
" -34.066994 ]\n",
|
||||||
|
" [-33.181664 -33.181664 -33.181664 ... -33.181664 -33.181664\n",
|
||||||
|
" -33.181664 ]]]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# We can now examine this data more carefully.\n",
|
||||||
|
"print(temp.units)\n",
|
||||||
|
"print(temp.shape)\n",
|
||||||
|
"print(temp[:])\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 11,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"-34.926773\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Let's be a little more restrained... how about all the data at the first lat/lon pair?\n",
|
||||||
|
"print(temp[0,0,0])\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 12,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"90.0\n",
|
||||||
|
"0.0\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# That seems pretty chilly! What are the lat/lon values?\n",
|
||||||
|
"lat = fileobj.variables[\"lat\"]\n",
|
||||||
|
"lon = fileobj.variables[\"lon\"]\n",
|
||||||
|
"\n",
|
||||||
|
"print(lat[0])\n",
|
||||||
|
"print(lon[0])\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Okay, that's reasonable for the North Pole.\n",
|
||||||
|
"# This grid is 2.5 degrees... let's find out what Seattle's weather was like!\n",
|
||||||
|
"\n",
|
||||||
|
"# Seattle is at approximately 47.5 N and 122.5 W.\n",
|
||||||
|
"\n",
|
||||||
|
"# This dataset's lon starts at 0 and counts up to 360.\n",
|
||||||
|
"# So 122.25 W corresponds to 360-122.5 = 237.5.\n",
|
||||||
|
"\n",
|
||||||
|
"# Remember, lat and lon are those weird data types:\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 13,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[ 90. 87.5 85. 82.5 80. 77.5 75. 72.5 70. 67.5 65. 62.5\n",
|
||||||
|
" 60. 57.5 55. 52.5 50. 47.5 45. 42.5 40. 37.5 35. 32.5\n",
|
||||||
|
" 30. 27.5 25. 22.5 20. 17.5 15. 12.5 10. 7.5 5. 2.5\n",
|
||||||
|
" 0. -2.5 -5. -7.5 -10. -12.5 -15. -17.5 -20. -22.5 -25. -27.5\n",
|
||||||
|
" -30. -32.5 -35. -37.5 -40. -42.5 -45. -47.5 -50. -52.5 -55. -57.5\n",
|
||||||
|
" -60. -62.5 -65. -67.5 -70. -72.5 -75. -77.5 -80. -82.5 -85. -87.5\n",
|
||||||
|
" -90. ]\n",
|
||||||
|
"[ 0. 2.5 5. 7.5 10. 12.5 15. 17.5 20. 22.5 25. 27.5\n",
|
||||||
|
" 30. 32.5 35. 37.5 40. 42.5 45. 47.5 50. 52.5 55. 57.5\n",
|
||||||
|
" 60. 62.5 65. 67.5 70. 72.5 75. 77.5 80. 82.5 85. 87.5\n",
|
||||||
|
" 90. 92.5 95. 97.5 100. 102.5 105. 107.5 110. 112.5 115. 117.5\n",
|
||||||
|
" 120. 122.5 125. 127.5 130. 132.5 135. 137.5 140. 142.5 145. 147.5\n",
|
||||||
|
" 150. 152.5 155. 157.5 160. 162.5 165. 167.5 170. 172.5 175. 177.5\n",
|
||||||
|
" 180. 182.5 185. 187.5 190. 192.5 195. 197.5 200. 202.5 205. 207.5\n",
|
||||||
|
" 210. 212.5 215. 217.5 220. 222.5 225. 227.5 230. 232.5 235. 237.5\n",
|
||||||
|
" 240. 242.5 245. 247.5 250. 252.5 255. 257.5 260. 262.5 265. 267.5\n",
|
||||||
|
" 270. 272.5 275. 277.5 280. 282.5 285. 287.5 290. 292.5 295. 297.5\n",
|
||||||
|
" 300. 302.5 305. 307.5 310. 312.5 315. 317.5 320. 322.5 325. 327.5\n",
|
||||||
|
" 330. 332.5 335. 337.5 340. 342.5 345. 347.5 350. 352.5 355. 357.5]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# So let's save their values instead.\n",
|
||||||
|
"a = lat[:]\n",
|
||||||
|
"b = lon[:]\n",
|
||||||
|
"print(a)\n",
|
||||||
|
"print(b)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 17,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"(array([17]),)\n",
|
||||||
|
"(array([95]),)\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Now we can use np.where() to find the locations of the values in the dataset.\n",
|
||||||
|
"sealat = np.where(a == 47.5)\n",
|
||||||
|
"sealon = np.where(b == 237.5)\n",
|
||||||
|
"\n",
|
||||||
|
"print(sealat)\n",
|
||||||
|
"print(sealon)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 18,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[[1.5006493]]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Let's print it out!\n",
|
||||||
|
"print(temp[0,sealat, sealon])\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 19,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"b'Monthly Mean Air Temperature'\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# If you want the full name of a particular variable, long_name is useful!\n",
|
||||||
|
"print(fileobj.variables[\"air\"].long_name)\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>10.3 Writing a NetCDF File</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"Just as with normal files, we can write our own NetCDF files!\n",
|
||||||
|
"\n",
|
||||||
|
"You can create a NetCDF file object in write mode!"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 21,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[[ 0. 0.09983342 0.19866933 0.29552021 0.38941834 0.47942554\n",
|
||||||
|
" 0.56464247 0.64421769 0.71735609 0.78332691 0.84147098 0.89120736\n",
|
||||||
|
" 0.93203909 0.96355819 0.98544973 0.99749499 0.9995736 0.99166481\n",
|
||||||
|
" 0.97384763 0.94630009]\n",
|
||||||
|
" [ 0.90929743 0.86320937 0.8084964 0.74570521 0.67546318 0.59847214\n",
|
||||||
|
" 0.51550137 0.42737988 0.33498815 0.23924933 0.14112001 0.04158066\n",
|
||||||
|
" -0.05837414 -0.15774569 -0.2555411 -0.35078323 -0.44252044 -0.52983614\n",
|
||||||
|
" -0.61185789 -0.68776616]\n",
|
||||||
|
" [-0.7568025 -0.81827711 -0.87157577 -0.91616594 -0.95160207 -0.97753012\n",
|
||||||
|
" -0.993691 -0.99992326 -0.99616461 -0.98245261 -0.95892427 -0.92581468\n",
|
||||||
|
" -0.88345466 -0.83226744 -0.77276449 -0.70554033 -0.63126664 -0.55068554\n",
|
||||||
|
" -0.46460218 -0.37387666]\n",
|
||||||
|
" [-0.2794155 -0.1821625 -0.0830894 0.0168139 0.1165492 0.21511999\n",
|
||||||
|
" 0.31154136 0.40484992 0.49411335 0.57843976 0.6569866 0.72896904\n",
|
||||||
|
" 0.79366786 0.85043662 0.8987081 0.93799998 0.96791967 0.98816823\n",
|
||||||
|
" 0.99854335 0.99894134]\n",
|
||||||
|
" [ 0.98935825 0.96988981 0.94073056 0.90217183 0.85459891 0.79848711\n",
|
||||||
|
" 0.7343971 0.66296923 0.58491719 0.50102086 0.41211849 0.31909836\n",
|
||||||
|
" 0.22288991 0.12445442 0.02477543 -0.07515112 -0.17432678 -0.27176063\n",
|
||||||
|
" -0.36647913 -0.45753589]\n",
|
||||||
|
" [-0.54402111 -0.62507065 -0.69987469 -0.76768581 -0.82782647 -0.87969576\n",
|
||||||
|
" -0.92277542 -0.95663502 -0.98093623 -0.99543625 -0.99999021 -0.99455259\n",
|
||||||
|
" -0.97917773 -0.95401925 -0.91932853 -0.87545217 -0.82282859 -0.76198358\n",
|
||||||
|
" -0.69352508 -0.61813711]\n",
|
||||||
|
" [-0.53657292 -0.44964746 -0.35822928 -0.26323179 -0.16560418 -0.0663219\n",
|
||||||
|
" 0.03362305 0.13323204 0.23150983 0.32747444 0.42016704 0.50866146\n",
|
||||||
|
" 0.59207351 0.66956976 0.74037589 0.80378443 0.85916181 0.90595474\n",
|
||||||
|
" 0.94369567 0.9720075 ]\n",
|
||||||
|
" [ 0.99060736 0.99930939 0.99802665 0.98677196 0.96565778 0.93489506\n",
|
||||||
|
" 0.89479117 0.84574683 0.78825207 0.72288135 0.65028784 0.57119687\n",
|
||||||
|
" 0.48639869 0.39674057 0.30311836 0.20646748 0.10775365 0.00796318\n",
|
||||||
|
" -0.09190685 -0.19085858]\n",
|
||||||
|
" [-0.28790332 -0.38207142 -0.47242199 -0.55805227 -0.63810668 -0.71178534\n",
|
||||||
|
" -0.77835208 -0.83714178 -0.88756703 -0.92912401 -0.96139749 -0.98406501\n",
|
||||||
|
" -0.99690007 -0.99977443 -0.99265938 -0.97562601 -0.9488445 -0.91258245\n",
|
||||||
|
" -0.86720218 -0.81315711]\n",
|
||||||
|
" [-0.75098725 -0.68131377 -0.60483282 -0.52230859 -0.43456562 -0.34248062\n",
|
||||||
|
" -0.24697366 -0.14899903 -0.04953564 0.05042269 0.14987721 0.24783421\n",
|
||||||
|
" 0.34331493 0.43536536 0.52306577 0.60553987 0.68196362 0.75157342\n",
|
||||||
|
" 0.81367374 0.8676441 ]]\n",
|
||||||
|
"42.0\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"newfile = S.netcdf_file(\"new.nc\",mode=\"w\")\n",
|
||||||
|
"\n",
|
||||||
|
"# Let's start by putting in 10 latitude and 20 longitude values.\n",
|
||||||
|
"lat = np.arange(10)\n",
|
||||||
|
"lon = np.arange(10)\n",
|
||||||
|
"\n",
|
||||||
|
"# And maybe two different sets of data, one array and one scalar.\n",
|
||||||
|
"data1 = np.reshape(np.sin(np.arange(200)*0.1),(10,20))\n",
|
||||||
|
"data2 = 42.0\n",
|
||||||
|
"\n",
|
||||||
|
"print(data1)\n",
|
||||||
|
"print(data2)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 23,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# So far so good! Let's create the actual dimension information.\n",
|
||||||
|
"newfile.createDimension(\"lat\",len(lat))\n",
|
||||||
|
"newfile.createDimension(\"lon\",len(lon))\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Now the names of our variables!\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# And now we assign the actual values to our variables!\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# And assign some units!\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Add a title to finish up!\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Okay, so having done all that (don't worry if all the details are unclear - this is a fairly advanced topic that will take some practice!), let's try reading our values."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>10.4 NetCDF Example</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"Let's pull up some monthly mean surface air temperature data from our air.mon.mean.nc data file. These data come from the NCEP/NCAR Reanalysis 1."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"\n",
|
||||||
|
"# Let's take a look at the time units.\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Well, that seems confusing.\n",
|
||||||
|
"# Let's create a new version of the file where time just starts at 0.0, and change the units string so it just says 'hours'.\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# And let's test it!\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>10.5 Take-Home Points</h2>\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li>NetCDF is a powerful file type containing global attributes, variables, variable attributes, and dimensions.</li>\n",
|
||||||
|
" <li>We can read from NetCDF files using similar syntax to that for regular files.</li>\n",
|
||||||
|
" <li>Using attributes such as 'dimensions' and 'variables', we can learn about individual variables in the dataset.</li>\n",
|
||||||
|
" <li>We can also write to NetCDF files in a simlar way.</li>\n",
|
||||||
|
"</ul>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3 (ipykernel)",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python3"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 3
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython3",
|
||||||
|
"version": "3.11.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 4
|
||||||
|
}
|
||||||
339
python/atms-310/notebooks/Week 06 M.ipynb
Executable file
339
python/atms-310/notebooks/Week 06 M.ipynb
Executable file
@ -0,0 +1,339 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h1>13. More Adventures in OOP</h1>\n",
|
||||||
|
"<h2>10/30/2023</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"<h2>13.0 Last Time...</h2>\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li>A class can be created using a <b>class</b> statement followed by the name of the class.</li>\n",
|
||||||
|
" <li>Methods within a class definition are created using a <b>def</b> statement.</li>\n",
|
||||||
|
" <li><b>__init__</b> is typically the first method defined and is used to initialize the core features of the class.</li>\n",
|
||||||
|
"</ul>\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>13.1 OOP Example: Creating a Bibliography</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"Let's create a new class called <b>Article</b> that's similar to our book class from last time, but stores a scientific journal article instead of a book, and writes the bibiliography entry accordingly."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 5,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Start by defining a new class. (Remember, you need the 'object' argument.)\n",
|
||||||
|
"class Article(object):\n",
|
||||||
|
" def __init__(self, authlast, authfirst, arttitle, journtitle, volume, pages, year):\n",
|
||||||
|
" self.authlast = authlast\n",
|
||||||
|
" self.authfirst = authfirst\n",
|
||||||
|
" self.arttitle = arttitle\n",
|
||||||
|
" self.journtitle = journtitle\n",
|
||||||
|
" self.volume = volume\n",
|
||||||
|
" self.pages = pages\n",
|
||||||
|
" self.year = year\n",
|
||||||
|
" # Let's create the make_authoryear and write_bib_entry methods from before.\n",
|
||||||
|
" def write_bib_entry(self):\n",
|
||||||
|
" \n",
|
||||||
|
" # We won't need any additional arguments here, since it's all handled above.\n",
|
||||||
|
" return self.authlast + ',' + self.authfirst + ',' + self.arttitle + ',' + self.journtitle + ',' + self.volume + ',' + self.pages + ',' + self.year\n",
|
||||||
|
" def authyear(self):\n",
|
||||||
|
" self.authyear = self.authlast + '('+self.year +')'"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 6,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"<__main__.Article object at 0x7f0511dc9dd0>\n",
|
||||||
|
"brooks,harold,on the tornado thingies,journal,19,310-319,2004\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# And a test!\n",
|
||||||
|
"tornado = Article(\"brooks\", 'harold', \"on the tornado thingies\", \"journal\", \"19\", \"310-319\", \"2004\")\n",
|
||||||
|
"print(tornado)\n",
|
||||||
|
"print(tornado.write_bib_entry())\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Let's also bring <b>Book</b> and our two instances of Book back from last lecture:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 9,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"class Book(object):\n",
|
||||||
|
" \n",
|
||||||
|
" def __init__(self, authlast, authfirst, \\\n",
|
||||||
|
" title, place, publisher, year):\n",
|
||||||
|
" self.authlast = authlast\n",
|
||||||
|
" self.authfirst = authfirst\n",
|
||||||
|
" self.title = title\n",
|
||||||
|
" self.place = place\n",
|
||||||
|
" self.publisher = publisher\n",
|
||||||
|
" self.year = year\n",
|
||||||
|
" \n",
|
||||||
|
" def write_bib_entry(self): \n",
|
||||||
|
" return self.authlast \\\n",
|
||||||
|
" + ', ' + self.authfirst \\\n",
|
||||||
|
" + ', ' + self.title \\\n",
|
||||||
|
" + ', ' + self.place \\\n",
|
||||||
|
" + ': ' + self.publisher + ', '\\\n",
|
||||||
|
" + self.year + '.'\n",
|
||||||
|
" def writebibalph(self):\n",
|
||||||
|
" self.sortentriesalph()\n",
|
||||||
|
" output=''\n",
|
||||||
|
" for i in self.entries:\n",
|
||||||
|
" output = output+i.writebibalph()+\"\\n\\n\"\n",
|
||||||
|
" return output\n",
|
||||||
|
" def sortentriesalph(self):\n",
|
||||||
|
" self.entries = sorted(self.entries,key=op.attrgetter('authlast','authfirst'))\n",
|
||||||
|
"beauty = Book(\"Dubay\",\"Thomas\" \\\n",
|
||||||
|
" , \"The Evidential Power of Beauty\" \\\n",
|
||||||
|
" , \"San Francisco\" \\\n",
|
||||||
|
" , \"Ignatius Press\", \"1999\")\n",
|
||||||
|
"\n",
|
||||||
|
"pynut = Book(\"Martelli\", \"Alex\" \\\n",
|
||||||
|
" , \"Python in a Nutshell\" \\\n",
|
||||||
|
" , \"Sebastopol, CA\" \\\n",
|
||||||
|
" , \"O'Reilly Media, Inc.\", \"2003\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Let's say we have a series of instances of the Book and Article classes that we want to pull together into one big bibliography. We'll create a new class called <b>Bibliography</b> for this task, and within Bibliography's definition will be two modules: one that initializes the class with everything we need, and one that sorts all entries alphabetically.\n",
|
||||||
|
"\n",
|
||||||
|
"To do this, we'll need some additional tools. One useful package to import here is called <b>operator</b>, which contains a useful function called <b>attrgetter</b>, which will pull a list of attributes out of an item in question. There are other ways of doing the same thing, but operator.attrgetter() will save us a lot of time! \n",
|
||||||
|
"\n",
|
||||||
|
"We'll also want to make use of <b>sorted()</b>, which is a function that sorts all entries (either alphabetically or numerically) according to a key we specify, which in this case will be the last name and the first name of the author (just in case we have multiple authors with the same last name)."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 2,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# We'll need the operator package.\n",
|
||||||
|
"import operator as op\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# Define our Bibliography class.\n",
|
||||||
|
"class bib(object):\n",
|
||||||
|
" # Initialize the class.\n",
|
||||||
|
" def __init__(self,entries):\n",
|
||||||
|
" self.entries = entries\n",
|
||||||
|
" \n",
|
||||||
|
" # Sort the entries alphabetically.\n",
|
||||||
|
" def sortentriesalph(self):\n",
|
||||||
|
" self.entries = sorted(self.entries,key=op.attrgetter('authlast','authfirst'))\n",
|
||||||
|
" # Now, write a bibliography in alphabetical order.\n",
|
||||||
|
" def writebibalph(self):\n",
|
||||||
|
" self.sortentriesalph()\n",
|
||||||
|
" output=''\n",
|
||||||
|
" for i in self.entries:\n",
|
||||||
|
" output = output+i.writebibalph()+\"\\n\\n\"\n",
|
||||||
|
" return output"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 7,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"ename": "AttributeError",
|
||||||
|
"evalue": "'Book' object has no attribute 'entries'",
|
||||||
|
"output_type": "error",
|
||||||
|
"traceback": [
|
||||||
|
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
|
||||||
|
"\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)",
|
||||||
|
"\u001b[1;32m/home/nik/data/python/notebooks/Week 06 M.ipynb Cell 9\u001b[0m line \u001b[0;36m2\n\u001b[1;32m <a href='vscode-notebook-cell:/home/nik/data/python/notebooks/Week%2006%20M.ipynb#X11sZmlsZQ%3D%3D?line=0'>1</a>\u001b[0m a \u001b[39m=\u001b[39m bib([beauty,pynut,tornado])\n\u001b[0;32m----> <a href='vscode-notebook-cell:/home/nik/data/python/notebooks/Week%2006%20M.ipynb#X11sZmlsZQ%3D%3D?line=1'>2</a>\u001b[0m b \u001b[39m=\u001b[39m a\u001b[39m.\u001b[39;49mwritebibalph()\n\u001b[1;32m <a href='vscode-notebook-cell:/home/nik/data/python/notebooks/Week%2006%20M.ipynb#X11sZmlsZQ%3D%3D?line=2'>3</a>\u001b[0m \u001b[39mprint\u001b[39m(b)\n",
|
||||||
|
"\u001b[1;32m/home/nik/data/python/notebooks/Week 06 M.ipynb Cell 9\u001b[0m line \u001b[0;36m1\n\u001b[1;32m <a href='vscode-notebook-cell:/home/nik/data/python/notebooks/Week%2006%20M.ipynb#X11sZmlsZQ%3D%3D?line=16'>17</a>\u001b[0m output\u001b[39m=\u001b[39m\u001b[39m'\u001b[39m\u001b[39m'\u001b[39m\n\u001b[1;32m <a href='vscode-notebook-cell:/home/nik/data/python/notebooks/Week%2006%20M.ipynb#X11sZmlsZQ%3D%3D?line=17'>18</a>\u001b[0m \u001b[39mfor\u001b[39;00m i \u001b[39min\u001b[39;00m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39mentries:\n\u001b[0;32m---> <a href='vscode-notebook-cell:/home/nik/data/python/notebooks/Week%2006%20M.ipynb#X11sZmlsZQ%3D%3D?line=18'>19</a>\u001b[0m output \u001b[39m=\u001b[39m output\u001b[39m+\u001b[39mi\u001b[39m.\u001b[39;49mwritebibalph()\u001b[39m+\u001b[39m\u001b[39m\"\u001b[39m\u001b[39m\\n\u001b[39;00m\u001b[39m\\n\u001b[39;00m\u001b[39m\"\u001b[39m\n\u001b[1;32m <a href='vscode-notebook-cell:/home/nik/data/python/notebooks/Week%2006%20M.ipynb#X11sZmlsZQ%3D%3D?line=19'>20</a>\u001b[0m \u001b[39mreturn\u001b[39;00m output\n",
|
||||||
|
"\u001b[1;32m/home/nik/data/python/notebooks/Week 06 M.ipynb Cell 9\u001b[0m line \u001b[0;36m2\n\u001b[1;32m <a href='vscode-notebook-cell:/home/nik/data/python/notebooks/Week%2006%20M.ipynb#X11sZmlsZQ%3D%3D?line=18'>19</a>\u001b[0m \u001b[39mdef\u001b[39;00m \u001b[39mwritebibalph\u001b[39m(\u001b[39mself\u001b[39m):\n\u001b[0;32m---> <a href='vscode-notebook-cell:/home/nik/data/python/notebooks/Week%2006%20M.ipynb#X11sZmlsZQ%3D%3D?line=19'>20</a>\u001b[0m \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49msortentriesalph()\n\u001b[1;32m <a href='vscode-notebook-cell:/home/nik/data/python/notebooks/Week%2006%20M.ipynb#X11sZmlsZQ%3D%3D?line=20'>21</a>\u001b[0m output\u001b[39m=\u001b[39m\u001b[39m'\u001b[39m\u001b[39m'\u001b[39m\n\u001b[1;32m <a href='vscode-notebook-cell:/home/nik/data/python/notebooks/Week%2006%20M.ipynb#X11sZmlsZQ%3D%3D?line=21'>22</a>\u001b[0m \u001b[39mfor\u001b[39;00m i \u001b[39min\u001b[39;00m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39mentries:\n",
|
||||||
|
"\u001b[1;32m/home/nik/data/python/notebooks/Week 06 M.ipynb Cell 9\u001b[0m line \u001b[0;36m2\n\u001b[1;32m <a href='vscode-notebook-cell:/home/nik/data/python/notebooks/Week%2006%20M.ipynb#X11sZmlsZQ%3D%3D?line=24'>25</a>\u001b[0m \u001b[39mdef\u001b[39;00m \u001b[39msortentriesalph\u001b[39m(\u001b[39mself\u001b[39m):\n\u001b[0;32m---> <a href='vscode-notebook-cell:/home/nik/data/python/notebooks/Week%2006%20M.ipynb#X11sZmlsZQ%3D%3D?line=25'>26</a>\u001b[0m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39mentries \u001b[39m=\u001b[39m \u001b[39msorted\u001b[39m(\u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49mentries,key\u001b[39m=\u001b[39mop\u001b[39m.\u001b[39mattrgetter(\u001b[39m'\u001b[39m\u001b[39mauthlast\u001b[39m\u001b[39m'\u001b[39m,\u001b[39m'\u001b[39m\u001b[39mauthfirst\u001b[39m\u001b[39m'\u001b[39m))\n",
|
||||||
|
"\u001b[0;31mAttributeError\u001b[0m: 'Book' object has no attribute 'entries'"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"a = bib([beauty,pynut,tornado])\n",
|
||||||
|
"b = a.writebibalph()\n",
|
||||||
|
"print(b)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Why did we bother doing this? Because it really highlights the power of OOP over traditional, procedural programming. In a lot of languages, we'd have to write a function to format every source entry correctly, depending on the source type (e.g., article or book), which would result in a tree of <b>if</b> tests.\n",
|
||||||
|
"\n",
|
||||||
|
"Another big advantage? Adding another source type would require <b>no changes or additions to existing code</b>, just a new class definition."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>13.2 OOP Example: Creating a Class for Geoscience Work</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"Let's work through another application: as an example, we'll define a class called <b>SurfaceDomain</b> that describes surface domain instances. A domain would be a land/ocean surface where the spatial extent is described by a latitude-longitude grid. We'll instantiate the class by providing a vector of longitudes and latitudes; our surface domain will be a regular grid based on those vectors. We can then assign surface parameters (e.g., elevation, temperature, roughness, etc.) as instance attributes.\n",
|
||||||
|
"\n",
|
||||||
|
"It may be helpful here to think of how best to represent a latitude-longitude grid in code. Let's look at the following example:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Let's say we have 5 longitude values and 4 latitude values.\n",
|
||||||
|
"# We want something that's going to look like the following:\n",
|
||||||
|
"\n",
|
||||||
|
"# Longitude should look like this:\n",
|
||||||
|
"\n",
|
||||||
|
"[[0 1 2 3 4]\n",
|
||||||
|
" [0 1 2 3 4]\n",
|
||||||
|
" [0 1 2 3 4]\n",
|
||||||
|
" [0 1 2 3 4]]\n",
|
||||||
|
"\n",
|
||||||
|
"# Latitude should look like this:\n",
|
||||||
|
"\n",
|
||||||
|
"[[0 0 0 0 0]\n",
|
||||||
|
" [1 1 1 1 1]\n",
|
||||||
|
" [2 2 2 2 2]\n",
|
||||||
|
" [3 3 3 3 3]]"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"There's a function in NumPy built in for this called <b>meshgrid</b>: given a longitude array and a latitude array, it will create a nice grid combining the two.\n",
|
||||||
|
"\n",
|
||||||
|
"Let's start our class definition."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 36,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import numpy as np\n",
|
||||||
|
"\n",
|
||||||
|
"class SurfaceDomain(object):\n",
|
||||||
|
" def __init__(self, lon, lat):\n",
|
||||||
|
" \n",
|
||||||
|
" # Let's make sure that latitude and longitude \n",
|
||||||
|
" self.lon = np.array(lon)\n",
|
||||||
|
" self.lat = np.array(lat)\n",
|
||||||
|
" [xall,yall] = np.meshgrid(self.lon,self.lat)\n",
|
||||||
|
" self.lonall = xall\n",
|
||||||
|
" self.latall = yall\n",
|
||||||
|
" del xall,yall\n",
|
||||||
|
" # are in array format.\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"We can then begin to manipulate elements of this domain individually or collectively (e.g., interpolation, etc.)."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 38,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[[1 2 3 4 5]\n",
|
||||||
|
" [1 2 3 4 5]\n",
|
||||||
|
" [1 2 3 4 5]\n",
|
||||||
|
" [1 2 3 4 5]]\n",
|
||||||
|
"[[0 0 0 0 0]\n",
|
||||||
|
" [1 1 1 1 1]\n",
|
||||||
|
" [2 2 2 2 2]\n",
|
||||||
|
" [3 3 3 3 3]]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"lon = [1,2,3,4,5]\n",
|
||||||
|
"lat = [0,1,2,3]\n",
|
||||||
|
"\n",
|
||||||
|
"a = SurfaceDomain(lon,lat)\n",
|
||||||
|
"print(a.lonall)\n",
|
||||||
|
"print(a.latall)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>13.3 Take-Home Points</h2>\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li>The <b>operator</b> package enables us to use a function called <b>attrgetter()</b> to grab attribute information from various classes.</li>\n",
|
||||||
|
" <li>The <b>sorted()</b> function lets us sort data alphabetically or numerically as needed.</li>\n",
|
||||||
|
" <li>NumPy's <b>meshgrid()</b> module lets us create a grid from lat/lon vectors.</li> \n",
|
||||||
|
"</ul>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3 (ipykernel)",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python3"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 3
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython3",
|
||||||
|
"version": "3.11.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 4
|
||||||
|
}
|
||||||
1666
python/atms-310/notebooks/Week 06 W.ipynb
Executable file
1666
python/atms-310/notebooks/Week 06 W.ipynb
Executable file
File diff suppressed because one or more lines are too long
772
python/atms-310/notebooks/Week 08 F.ipynb
Executable file
772
python/atms-310/notebooks/Week 08 F.ipynb
Executable file
File diff suppressed because one or more lines are too long
442
python/atms-310/notebooks/Week 08 M.ipynb
Executable file
442
python/atms-310/notebooks/Week 08 M.ipynb
Executable file
@ -0,0 +1,442 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h1>15. Missing Values</h1>\n",
|
||||||
|
"<h2>11/13/2023</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"<h2>15.0 Last Time...</h2>\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li><b>Pandas</b> is a useful way of working with CSV data!</li>\n",
|
||||||
|
" <li>A <b>dataframe</b> is an object that contains rows and columns, much like an Excel spreadsheet.</li>\n",
|
||||||
|
" <li><b>loc()</b> will let you identify individual rows, columns, or values.</li>\n",
|
||||||
|
" <li><b>describe()</b> summarizes statistics for a specified section of a dataframe.</li>\n",
|
||||||
|
" <li><b>read_csv()</b> will read in a CSV file specified by a file location.</li>\n",
|
||||||
|
" <li><b>groupby()</b> carries out specific operations on groupings within a dataframe.</li>\n",
|
||||||
|
"</ul>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>15.1 Masked Arrays</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"<b>Masked</b> arrays are just like normal arrays, except that they have a \"mask\" attribute to tell you which elements are bad.\n",
|
||||||
|
"\n",
|
||||||
|
"Recall how arrays normally work:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 2,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[[1 2 3]\n",
|
||||||
|
" [4 5 6]]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Let's create a 2D array that contains the numbers 1-6.\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"import pandas as pd\n",
|
||||||
|
"\n",
|
||||||
|
"a = np.array([[1,2,3],[4,5,6]])\n",
|
||||||
|
"print(a)\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"If we have some information that maybe the last two values are suspicious and may consist of bad data, we can create a <b>mask</b> of bad values that will travel with the array. Elements in the array whose mask value corresponds to \"bad\" are treated as if they did not exist, and operations using the array automatically consider that mask of bad values.\n",
|
||||||
|
"\n",
|
||||||
|
"This is extremely useful! Sometimes we have a dataset that's read-only, or we want to be aware of precisely which data are suspect, so instead of deleting them, we just keep all information and have a flag on which values are bad.\n",
|
||||||
|
"\n",
|
||||||
|
"For this purpose, NumPy has a function called <b>numpy.ma</b>."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 7,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[[1 2 3]\n",
|
||||||
|
" [4 -- --]]\n",
|
||||||
|
"[[False False False]\n",
|
||||||
|
" [False True True]]\n",
|
||||||
|
"[[1 2 3]\n",
|
||||||
|
" [4 5 6]]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"import numpy.ma as ma\n",
|
||||||
|
" # This saves us having to type 'np.' at the start of every instance of numpy.ma.\n",
|
||||||
|
"\n",
|
||||||
|
"a = np.array([[1,2,3],[4,5,6]])\n",
|
||||||
|
"b = ma.masked_greater(a,4)\n",
|
||||||
|
"\n",
|
||||||
|
"print(b)\n",
|
||||||
|
"# Let's set our mask to everything greater than 4.\n",
|
||||||
|
"print(b.mask)\n",
|
||||||
|
"print(b.data)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 8,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[[3 6 9]\n",
|
||||||
|
" [12 -- --]]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Now, if we try to do an operation on our masked array:\n",
|
||||||
|
"print(b*3)\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"When we have a masked array, any operations applied to elements whose mask value is set to True will create a resulting array that also has the corresponding elements' mask values set to True. Masked arrays thus transparently deal with missing data."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>15.2 Constructing and Deconstructing Masked Arrays</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"There are several different ways to construct a masked array; we saw one example above, but (as always!) Python provides us with options.\n",
|
||||||
|
"\n",
|
||||||
|
"We can explicitly specify a mask!"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 10,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[-- -- 3]\n",
|
||||||
|
"[1 2 3]\n",
|
||||||
|
"[ True True False]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"a = ma.masked_array(data=[1,2,3],mask=[True,True,False])\n",
|
||||||
|
"print(a)\n",
|
||||||
|
"print(a.data)\n",
|
||||||
|
"print(a.mask)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"A lot of the time, we'll determine whether or not data values should be masked on the basis of some logical test (e.g., whether data values are beyond an acceptable value - like negative rainfall amounts!).\n",
|
||||||
|
"\n",
|
||||||
|
"We can make a masked array by masking values based on conditions! This can be done with some specific functions like <b>numpy.ma.masked_greater()</b> and <b>numpy.ma.masked_where()</b>."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 13,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[1 2 3 -- --]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Mask all values greater than 3.\n",
|
||||||
|
"data = np.array([1,2,3,4,5])\n",
|
||||||
|
"a = ma.masked_greater(data,3)\n",
|
||||||
|
"print(a)\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 14,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[1 2 -- -- 5]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"# Mask all values greater than 2 and less than 5.\n",
|
||||||
|
"b = ma.masked_where(np.logical_and(data>2,data<5),data)\n",
|
||||||
|
"print(b)\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Sometimes we might want to export our results to a file that doesn't support object attributes (for example, a text or comma-separated value file). In those cases, it makes sense to replace masked values with some value that we know is nonsense, which we can do using <b>numpy.ma.filled()</b>."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 17,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[-- -- 3.0]\n",
|
||||||
|
"[-1.e+23 -1.e+23 3.e+00]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"c = ma.masked_array(data=[1.,2.,3.],mask=[True,True,False],fill_value=-1e+23)\n",
|
||||||
|
"print(c)\n",
|
||||||
|
"\n",
|
||||||
|
"d = ma.filled(c)\n",
|
||||||
|
"print(d)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>15.3 An Example</h2>\n",
|
||||||
|
"\n",
|
||||||
|
"As an example, let's revisit the <b>air.mon.mean.nc</b> NetCDF file from before. This dataset consists of air temperature in Celsius for the global domain. Let's look at the first time slice of this dataset and mask out temperatures in all locations greater than 45N and less than 45S, then convert the remaining temperatures to Kelvins (K = 273.15 + C)."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 20,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# First, import the important packages.\n",
|
||||||
|
"import scipy.io as sc\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# Open the file in read-only mode.\n",
|
||||||
|
"fileobj = sc.netcdf_file(\"../datasets/air.mon.mean.nc\",mode=\"r\")\n",
|
||||||
|
"\n",
|
||||||
|
"# Create three variables: temp, lat, and lon.\n",
|
||||||
|
" # Remember, we only want the first time step!\n",
|
||||||
|
"temp = fileobj.variables[\"air\"][0,:,:]\n",
|
||||||
|
"lat = fileobj.variables[\"lat\"][:]\n",
|
||||||
|
"lon = fileobj.variables[\"lon\"][:]\n",
|
||||||
|
"\n",
|
||||||
|
"# Use meshgrid() to create a lat-lon grid.\n",
|
||||||
|
"\n",
|
||||||
|
"[lonall,latall] = np.meshgrid(lon,lat)\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<b>1. With the above code to get you started, create a masked array called ma_temp that masks all latitudes greater than 45 and less than -45.</b>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 27,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[[-- -- -- ... -- -- --]\n",
|
||||||
|
" [-- -- -- ... -- -- --]\n",
|
||||||
|
" [-- -- -- ... -- -- --]\n",
|
||||||
|
" ...\n",
|
||||||
|
" [-- -- -- ... -- -- --]\n",
|
||||||
|
" [-- -- -- ... -- -- --]\n",
|
||||||
|
" [-- -- -- ... -- -- --]]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"ma_temp = ma.masked_where(np.logical_or(latall>45,latall<-45),temp)\n",
|
||||||
|
"print(x)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<b>2. Next, convert all temperatures in the unmasked region (between 45N and 45S) to Kelvins.</b>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 32,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[[-- -- -- ... -- -- --]\n",
|
||||||
|
" [-- -- -- ... -- -- --]\n",
|
||||||
|
" [-- -- -- ... -- -- --]\n",
|
||||||
|
" ...\n",
|
||||||
|
" [-- -- -- ... -- -- --]\n",
|
||||||
|
" [-- -- -- ... -- -- --]\n",
|
||||||
|
" [-- -- -- ... -- -- --]]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"ma_temp = ma_temp+273.15\n",
|
||||||
|
"print(kelvin)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"You can check the results with the following code:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 33,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"North pole: [-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --\n",
|
||||||
|
" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --\n",
|
||||||
|
" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --\n",
|
||||||
|
" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --\n",
|
||||||
|
" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --\n",
|
||||||
|
" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --]\n",
|
||||||
|
"South pole: [-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --\n",
|
||||||
|
" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --\n",
|
||||||
|
" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --\n",
|
||||||
|
" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --\n",
|
||||||
|
" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --\n",
|
||||||
|
" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --]\n",
|
||||||
|
"Equator: [298.989990234375 298.8916015625 298.92547607421875 299.78387451171875\n",
|
||||||
|
" 297.4780578613281 294.6690368652344 295.40869140625 296.71514892578125\n",
|
||||||
|
" 296.8448181152344 296.437744140625 295.9793395996094 293.3296813964844\n",
|
||||||
|
" 292.00128173828125 294.366455078125 293.1861267089844 294.57452392578125\n",
|
||||||
|
" 301.221923828125 301.32000732421875 298.9042053222656 298.9080505371094\n",
|
||||||
|
" 298.2835388183594 298.419677734375 298.5970764160156 298.6822509765625\n",
|
||||||
|
" 298.8238525390625 298.6919250488281 298.71484375 298.830322265625\n",
|
||||||
|
" 299.1283874511719 298.9522399902344 298.6025695800781 298.3016052246094\n",
|
||||||
|
" 298.3628845214844 298.5619201660156 298.70159912109375 298.83966064453125\n",
|
||||||
|
" 298.58514404296875 298.8529052734375 298.94903564453125 298.3051452636719\n",
|
||||||
|
" 296.6951599121094 296.3338623046875 298.24224853515625 298.41387939453125\n",
|
||||||
|
" 296.9270935058594 294.44805908203125 294.5732116699219 297.2270812988281\n",
|
||||||
|
" 296.748046875 297.1932067871094 298.6135559082031 298.6080627441406\n",
|
||||||
|
" 298.5787048339844 297.7358093261719 298.6219177246094 300.23065185546875\n",
|
||||||
|
" 300.4396667480469 300.650634765625 300.4158020019531 300.04449462890625\n",
|
||||||
|
" 300.2264404296875 300.44580078125 300.19580078125 299.89288330078125\n",
|
||||||
|
" 299.8716125488281 299.91741943359375 299.8864440917969 299.64739990234375\n",
|
||||||
|
" 299.6064453125 299.6180725097656 299.51739501953125 299.43450927734375\n",
|
||||||
|
" 299.3219299316406 299.2790222167969 299.062255859375 299.01611328125\n",
|
||||||
|
" 299.1012878417969 299.0425720214844 299.07806396484375 298.74322509765625\n",
|
||||||
|
" 298.59063720703125 298.52288818359375 298.23419189453125\n",
|
||||||
|
" 298.3409729003906 298.168701171875 298.0899963378906 298.0496826171875\n",
|
||||||
|
" 297.89288330078125 298.1625671386719 297.9141845703125 297.8422546386719\n",
|
||||||
|
" 297.8786926269531 297.53643798828125 297.52288818359375 297.2799987792969\n",
|
||||||
|
" 297.0796813964844 297.2138671875 297.080322265625 296.75933837890625\n",
|
||||||
|
" 296.722900390625 296.6477355957031 296.57708740234375 296.4858093261719\n",
|
||||||
|
" 296.3219299316406 296.5787048339844 296.8248291015625 297.05352783203125\n",
|
||||||
|
" 296.7248229980469 297.19903564453125 297.5367736816406 297.294189453125\n",
|
||||||
|
" 297.6383972167969 293.062255859375 290.7722473144531 295.3493347167969\n",
|
||||||
|
" 296.72320556640625 296.6377258300781 296.75933837890625\n",
|
||||||
|
" 296.89935302734375 297.1480712890625 296.15484619140625 296.649658203125\n",
|
||||||
|
" 296.330322265625 296.31549072265625 297.60162353515625 297.9100036621094\n",
|
||||||
|
" 298.46514892578125 298.4815979003906 298.3829040527344 298.1735534667969\n",
|
||||||
|
" 297.87225341796875 298.0712890625 298.0290222167969 297.97064208984375\n",
|
||||||
|
" 298.06097412109375 298.2054748535156 297.97967529296875 298.169677734375\n",
|
||||||
|
" 298.4061279296875 298.37774658203125 298.5574035644531 298.3951416015625\n",
|
||||||
|
" 298.58740234375 298.7112731933594]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"print('North pole: ',ma_temp[0,:])\n",
|
||||||
|
"print('South pole: ',ma_temp[-1,:])\n",
|
||||||
|
"print('Equator: ',ma_temp[36,:])"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<h2>15.4 Take-Home Points</h2>\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li>A masked array has a <b>mask</b> attribute that allows us to identify suspicious or unwanted data.</li>\n",
|
||||||
|
" <li>We can use direct assignment, assignment by condition, and filling to create a masked array.</li>\n",
|
||||||
|
"</ul>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3 (ipykernel)",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python3"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 3
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython3",
|
||||||
|
"version": "3.11.5"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 4
|
||||||
|
}
|
||||||
502
python/atms-310/notebooks/Week 08 W.ipynb
Executable file
502
python/atms-310/notebooks/Week 08 W.ipynb
Executable file
File diff suppressed because one or more lines are too long
306
python/atms-310/notebooks/Week 09 M.ipynb
Executable file
306
python/atms-310/notebooks/Week 09 M.ipynb
Executable file
File diff suppressed because one or more lines are too long
13
python/atms-310/test.py
Executable file
13
python/atms-310/test.py
Executable file
@ -0,0 +1,13 @@
|
|||||||
|
butt = [1,3,34,69420,"balls"]
|
||||||
|
for i in range(len(butt)):
|
||||||
|
butt[i] = butt[i]*10
|
||||||
|
print(butt[i])
|
||||||
|
|
||||||
|
# example of mutating a list, cuz you can do that
|
||||||
|
|
||||||
|
booty = (1,2,3,4,5,"nuts")
|
||||||
|
for n in range(len(butt)):
|
||||||
|
booty[n] = booty[n]*12
|
||||||
|
print(booty[n])
|
||||||
|
|
||||||
|
# example of not mutating a tuple, cuz you cant do that
|
||||||
17
python/other/lab6.py
Executable file
17
python/other/lab6.py
Executable file
@ -0,0 +1,17 @@
|
|||||||
|
import numpy as np
|
||||||
|
|
||||||
|
data = [384, 381, 384, 383, 385, 382, 384, 383, 384, 382]
|
||||||
|
|
||||||
|
# print(np.average(data))
|
||||||
|
# print(np.std(data))
|
||||||
|
|
||||||
|
data2 = [1.32, 1.40, 1.48, 1.35]
|
||||||
|
|
||||||
|
print(np.average(data2))
|
||||||
|
print(np.std(data2))
|
||||||
|
|
||||||
|
data3 = [0.27,0.30,0.30,0.31,0.29,0.27]
|
||||||
|
|
||||||
|
# print(np.average(data3))
|
||||||
|
# print(np.std(data3))
|
||||||
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user