~kris/dots

srice

ref: 178c9a25a484ead715392d50e21d03df486b8b41 srice/.config/.mksh/sci.sh -rw-r--r-- 6.3 KiB
178c9a25 — Kris Yotam conky: sync proper config from moirai (was the greenred variant) 2 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
# sci -- scientific computing aliases and functions

# ============================================================================
# QUICK COMPUTATION
# ============================================================================
alias q='qalc'
alias qc='qalc --terse'
alias oct='octave --quiet --eval'
alias bc='bc -l'

# ============================================================================
# CSV / DATA TOOLS
# ============================================================================
alias cl='csvlook'
alias cs='csvstat'
alias mlc='mlr --csv'
alias mlj='mlr --json'
alias mlp='mlr --icsv --opprint'
alias dm='datamash'
alias dmh='datamash -H'

# ============================================================================
# PAPER MANAGEMENT (papis)
# ============================================================================
alias pa='papis add --from arxiv'
alias pd='papis add --from doi'
alias po='papis open'
alias pe='papis edit'
alias pb='papis browse'

# ============================================================================
# arXiv
# ============================================================================
alias arxs='arxiv-search'

# ============================================================================
# SLURM (if on cluster)
# ============================================================================
alias sq='squeue -u $USER'
alias sqa='squeue -u $USER -o "%.8i %.9P %.30j %.2t %.10M %.6D %R"'

# ============================================================================
# FUNCTIONS
# ============================================================================

# calc -- python calculator with math imported
calc() {
    python3 -c "from math import *; print($*)"
}

# doi2bib -- DOI to BibTeX via content negotiation (zero dependencies)
doi2bib() {
    curl -sLH "Accept: application/x-bibtex" "https://doi.org/$1"
}

# doi2txt -- DOI to formatted citation
doi2txt() {
    curl -sLH "Accept: text/x-bibliography; style=apa" "https://doi.org/$1"
}

# arxdl -- download arXiv paper by ID
arxdl() {
    typeset id="$1"
    id="${id##*/abs/}"
    id="${id%.pdf}"
    python3 -c "
import arxiv
from urllib.request import urlretrieve
paper = next(arxiv.Client().results(arxiv.Search(id_list=['$id'])))
safe = ''.join(c if c.isalnum() or c in ' -_' else '' for c in paper.title)[:80]
fname = f'$id - {safe}.pdf'
urlretrieve(paper.pdf_url, fname)
print(f'Saved: {fname}')
"
}

# s2search -- Semantic Scholar search
s2search() {
    typeset query
    query=$(echo "$*" | tr ' ' '+')
    curl -s "https://api.semanticscholar.org/graph/v1/paper/search?query=$query&limit=10&fields=title,year,citationCount,url" | python3 -c "
import json, sys
data = json.load(sys.stdin)
for p in data.get('data', []):
    print(f\"{p.get('citationCount',0):>6}  {p.get('year','')}  {p['title']}\")
"
}

# s2related -- find related papers
s2related() {
    python3 -c "
from semanticscholar import SemanticScholar
s = SemanticScholar()
recs = s.get_recommended_papers('$1')
for r in recs[:10]:
    print(f'{r.citationCount:>6}  {r.year}  {r.title}')
"
}

# matmul -- matrix multiply
matmul() {
    python3 -c "import numpy as np; print(np.array($1) @ np.array($2))"
}

# eig -- eigenvalues
eig() {
    python3 -c "
import numpy as np
vals, vecs = np.linalg.eig(np.array($1))
print('Eigenvalues:', vals)
"
}

# det -- determinant
det() {
    python3 -c "import numpy as np; print(np.linalg.det(np.array($1)))"
}

# linsolve -- solve Ax=b
linsolve() {
    python3 -c "import numpy as np; print(np.linalg.solve(np.array($1), np.array($2)))"
}

# integrate -- numerical integration
integrate() {
    python3 -c "
from scipy.integrate import quad
import numpy as np
result, error = quad(lambda x: $1, $2, $3)
print(f'Result: {result:.10f}')
print(f'Error:  {error:.2e}')
"
}

# fft -- FFT from stdin data
fft() {
    python3 -c "
import numpy as np, sys
data = np.loadtxt(sys.stdin)
F = np.fft.rfft(data)
freq = np.fft.rfftfreq(len(data), d=1.0)
for f, a in zip(freq, np.abs(F)):
    print(f'{f:.6f}\t{a:.6f}')
"
}

# polyfit -- fit polynomial to two-column data from stdin
polyfit() {
    typeset degree="${1:-2}"
    python3 -c "
import numpy as np, sys
data = np.loadtxt(sys.stdin)
x, y = data[:,0], data[:,1]
coeffs = np.polyfit(x, y, $degree)
print('Coefficients:', coeffs)
p = np.poly1d(coeffs)
residuals = y - p(x)
print(f'R-squared: {1 - np.var(residuals)/np.var(y):.6f}')
"
}

# tplot -- terminal plot from stdin
tplot() {
    typeset title="${1:-Data}"
    python3 -c "
import plotext as plt, sys
data = [float(l.strip()) for l in sys.stdin if l.strip()]
plt.plot(data)
plt.title('$title')
plt.show()
"
}

# simbad -- look up astronomical object
simbad() {
    typeset ident
    ident=$(echo "$*" | tr ' ' '+')
    curl -s "https://simbad.u-strasbg.fr/simbad/sim-id?Ident=$ident&output.format=ASCII"
}

# apod -- NASA Astronomy Picture of the Day
apod() {
    typeset apod_date="${1:-$(date +%Y-%m-%d)}"
    curl -s "https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&date=$apod_date" | python3 -m json.tool
}

# fitsstats -- FITS file statistics
fitsstats() {
    python3 -c "
from astropy.io import fits
import numpy as np
data = fits.getdata('$1')
print(f'Shape: {data.shape}')
print(f'Min:   {np.nanmin(data):.4f}')
print(f'Max:   {np.nanmax(data):.4f}')
print(f'Mean:  {np.nanmean(data):.4f}')
print(f'Std:   {np.nanstd(data):.4f}')
"
}

# nf -- find notes with fzf
nf() {
    typeset notes_dir="${NOTES_DIR:-$HOME/notes}"
    typeset file
    file=$(find "$notes_dir" -name '*.md' -type f | \
        fzf --preview 'bat --color=always --style=numbers {}' \
            --preview-window=right:60%:wrap)
    [[ -n $file ]] && $EDITOR "$file"
}

# ns -- search note contents with fzf
ns() {
    typeset notes_dir="${NOTES_DIR:-$HOME/notes}"
    typeset match
    match=$(rg --line-number --no-heading --color=always "$1" "$notes_dir" | \
        fzf --ansi --delimiter=: \
            --preview 'bat --color=always --highlight-line {2} {1}')
    [[ -n $match ]] && $EDITOR "$(echo "$match" | cut -d: -f1)"
}

# nn -- new timestamped note
nn() {
    typeset notes_dir="${NOTES_DIR:-$HOME/notes}"
    typeset id=$(date +%Y%m%d%H%M%S)
    typeset title="${*:-Untitled}"
    typeset slug=$(echo "$title" | tr '[:upper:]' '[:lower:]' | tr ' ' '-' | tr -cd 'a-z0-9-')
    typeset file="$notes_dir/$id-$slug.md"
    printf -- '---\ntitle: %s\ndate: %s\ntags: []\n---\n\n' "$title" "$(date +%Y-%m-%dT%H:%M:%S)" > "$file"
    $EDITOR "$file"
}