py2ls 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- py2ls/.git/COMMIT_EDITMSG +1 -0
- py2ls/.git/FETCH_HEAD +1 -0
- py2ls/.git/HEAD +1 -0
- py2ls/.git/config +15 -0
- py2ls/.git/description +1 -0
- py2ls/.git/hooks/applypatch-msg.sample +15 -0
- py2ls/.git/hooks/commit-msg.sample +24 -0
- py2ls/.git/hooks/fsmonitor-watchman.sample +174 -0
- py2ls/.git/hooks/post-update.sample +8 -0
- py2ls/.git/hooks/pre-applypatch.sample +14 -0
- py2ls/.git/hooks/pre-commit.sample +49 -0
- py2ls/.git/hooks/pre-merge-commit.sample +13 -0
- py2ls/.git/hooks/pre-push.sample +53 -0
- py2ls/.git/hooks/pre-rebase.sample +169 -0
- py2ls/.git/hooks/pre-receive.sample +24 -0
- py2ls/.git/hooks/prepare-commit-msg.sample +42 -0
- py2ls/.git/hooks/push-to-checkout.sample +78 -0
- py2ls/.git/hooks/update.sample +128 -0
- py2ls/.git/index +0 -0
- py2ls/.git/info/exclude +6 -0
- py2ls/.git/logs/HEAD +1 -0
- py2ls/.git/logs/refs/heads/main +1 -0
- py2ls/.git/logs/refs/remotes/origin/HEAD +1 -0
- py2ls/.git/logs/refs/remotes/origin/main +1 -0
- py2ls/.git/objects/25/b796accd261b9135fd32a2c00785f68edf6c46 +0 -0
- py2ls/.git/objects/36/b4a1b7403abc6c360f8fe2cb656ab945254971 +0 -0
- py2ls/.git/objects/3f/d6561300938afbb3d11976cf9c8f29549280d9 +0 -0
- py2ls/.git/objects/58/20a729045d4dc7e37ccaf8aa8eec126850afe2 +0 -0
- py2ls/.git/objects/60/f273eb1c412d916fa3f11318a7da7a9911b52a +0 -0
- py2ls/.git/objects/61/570cec8c061abe74121f27f5face6c69b98f99 +0 -0
- py2ls/.git/objects/69/13c452ca319f7cbf6a0836dc10a5bb033c84e4 +0 -0
- py2ls/.git/objects/78/3d4167bc95c9d2175e0df03ef1c1c880ba75ab +0 -0
- py2ls/.git/objects/79/7ae089b2212a937840e215276005ce76881307 +0 -0
- py2ls/.git/objects/7e/5956c806b5edc344d46dab599dec337891ba1f +1 -0
- py2ls/.git/objects/8e/55a7d2b96184030211f20c9b9af201eefcac82 +0 -0
- py2ls/.git/objects/91/c69ad88fe0ba94aa7859fb5f7edac5e6f1a3f7 +0 -0
- py2ls/.git/objects/b0/56be4be89ba6b76949dd641df45bb7036050c8 +0 -0
- py2ls/.git/objects/b0/9cd7856d58590578ee1a4f3ad45d1310a97f87 +0 -0
- py2ls/.git/objects/d9/005f2cc7fc4e65f14ed5518276007c08cf2fd0 +0 -0
- py2ls/.git/objects/df/e0770424b2a19faf507a501ebfc23be8f54e7b +0 -0
- py2ls/.git/objects/e9/391ffe371f1cc43b42ef09b705d9c767c2e14f +0 -0
- py2ls/.git/objects/fc/292e793ecfd42240ac43be407023bd731fa9e7 +0 -0
- py2ls/.git/refs/heads/main +1 -0
- py2ls/.git/refs/remotes/origin/HEAD +1 -0
- py2ls/.git/refs/remotes/origin/main +1 -0
- py2ls/.gitattributes +2 -0
- py2ls/.gitignore +152 -0
- py2ls/LICENSE +201 -0
- py2ls/README.md +409 -0
- py2ls/__init__.py +17 -0
- py2ls/brain_atlas.py +145 -0
- py2ls/correlators.py +475 -0
- py2ls/dbhandler.py +97 -0
- py2ls/freqanalysis.py +800 -0
- py2ls/internet_finder.py +405 -0
- py2ls/ips.py +2844 -0
- py2ls/netfinder.py +780 -0
- py2ls/sleep_events_detectors.py +1350 -0
- py2ls/translator.py +686 -0
- py2ls/version.py +1 -0
- py2ls/wb_detector.py +169 -0
- py2ls-0.1.0.dist-info/METADATA +12 -0
- py2ls-0.1.0.dist-info/RECORD +64 -0
- py2ls-0.1.0.dist-info/WHEEL +4 -0
py2ls/README.md
ADDED
@@ -0,0 +1,409 @@
|
|
1
|
+
## ips
|
2
|
+
|
3
|
+
### listdir, basename, dirname, newfolder
|
4
|
+
|
5
|
+
e.g.,
|
6
|
+
|
7
|
+
```python
|
8
|
+
fpath = "....../"
|
9
|
+
ips.listdir(fpath, kind='pdf', sort_by="size", ascending=0, output = df)
|
10
|
+
```
|
11
|
+
|
12
|
+
it filters the ‘.pdf’ files, and sort by the (file-size/name, length of name, create_time, mod_time, last_open_time …) it returns a DataFrame or BoxList (setting by ‘output’)
|
13
|
+
|
14
|
+
```python
|
15
|
+
dir_data, dir_fig = newfolder(fpath, {'data', 'fig'}) # create folder
|
16
|
+
```
|
17
|
+
|
18
|
+
```python
|
19
|
+
finfo(fpath) # get info: size, creation time, mod time, parent_path, fname, kind...
|
20
|
+
```
|
21
|
+
|
22
|
+
```python
|
23
|
+
dir_lib(lib_of_interest) # get the fpath
|
24
|
+
```
|
25
|
+
|
26
|
+
|
27
|
+
|
28
|
+
### list_func/func_list (same)
|
29
|
+
|
30
|
+
list functions in a package
|
31
|
+
|
32
|
+
### fload, fsave, figsave
|
33
|
+
|
34
|
+
e.g.,
|
35
|
+
|
36
|
+
```python
|
37
|
+
fload(fpath, kind=None, **kwargs)
|
38
|
+
```
|
39
|
+
|
40
|
+
load file (docx, pdf, image, md, json,csv,txt, html, yaml, xml, xlsx…) or save file.
|
41
|
+
|
42
|
+
```python
|
43
|
+
# figsave, as used in matlab.
|
44
|
+
figsave(dir_save, "fname.pdf", dpi=300)
|
45
|
+
```
|
46
|
+
|
47
|
+
|
48
|
+
|
49
|
+
### pdf2img, img2pdf, docx2pdf
|
50
|
+
|
51
|
+
extract images from a PDF, or merge images into a pdf file
|
52
|
+
|
53
|
+
```python
|
54
|
+
pdf2img(dir_pdf, dir_save=None, page=None, kind="png",verbose=True, **kws)
|
55
|
+
pdf2img(fpath, page=[None, None]) # means extract all pages
|
56
|
+
# processing page: 1
|
57
|
+
# processing page: 2
|
58
|
+
# processing page: 3
|
59
|
+
# processing page: 4
|
60
|
+
# processing page: 5
|
61
|
+
|
62
|
+
```
|
63
|
+
|
64
|
+
```python
|
65
|
+
img2pdf(dir_img, kind="jpeg",page=None, dir_save=None, page_size="a4", dpi=300)
|
66
|
+
```
|
67
|
+
|
68
|
+
```python
|
69
|
+
docx2pdf(dir_docx, dir_save) # convert docx to pdf
|
70
|
+
```
|
71
|
+
|
72
|
+
### paper_size
|
73
|
+
|
74
|
+
quickly get the size info
|
75
|
+
|
76
|
+
```python
|
77
|
+
paper_size('a4') # [210, 297]
|
78
|
+
paper_size('card') # [85.6, 53.98]
|
79
|
+
```
|
80
|
+
|
81
|
+
|
82
|
+
|
83
|
+
### str2num, num2str, str2list
|
84
|
+
|
85
|
+
e.g.,
|
86
|
+
|
87
|
+
```python
|
88
|
+
str2num(“123.345 dollers”,2)# => 123.35 (float)
|
89
|
+
```
|
90
|
+
|
91
|
+
```python
|
92
|
+
str2list("abcd") # ['a','b','c','d']
|
93
|
+
```
|
94
|
+
|
95
|
+
```python
|
96
|
+
list2str(x_str)
|
97
|
+
```
|
98
|
+
|
99
|
+
|
100
|
+
|
101
|
+
### ssplit, sreplace
|
102
|
+
|
103
|
+
```python
|
104
|
+
sreplace(text, dict_replace=None, robust=True)
|
105
|
+
```
|
106
|
+
|
107
|
+
```python
|
108
|
+
ssplit(text, by="space", verbose=False, **kws) # by = "word", "sentence", ", ","num_strings","digital".....,"length", "upper followed lower", "lower followed upper"
|
109
|
+
```
|
110
|
+
|
111
|
+
```python
|
112
|
+
text = "The most pronounced physiological changes in sleep occur in the brain.[10] The brain uses significantly less energy during sleep than it does when awake, especially during non-REM sleep. In areas with reduced activity, the brain restores its supply of adenosine triphosphate (ATP), the molecule used for short-term storage and transport of energy.[11] In quiet waking, the brain is responsible for 20% of the body's energy use, thus this reduction has a noticeable effect on overall energy consumption.[12]"
|
113
|
+
ssplit(text, by=["[10]", "[11]", "[12]"])
|
114
|
+
# ['The most pronounced physiological changes in sleep occur in the brain.',
|
115
|
+
# ' The brain uses significantly less energy during sleep than it does when awake, especially during non-REM sleep. In areas with reduced activity, the brain restores its supply of adenosine triphosphate (ATP), the molecule used for short-term storage and transport of energy.',
|
116
|
+
# " In quiet waking, the brain is responsible for 20% of the body's energy use, thus this reduction has a noticeable effect on overall energy consumption.",
|
117
|
+
# '']
|
118
|
+
```
|
119
|
+
|
120
|
+
```python
|
121
|
+
ssplit(text[:30], by="len", length=5)
|
122
|
+
# ['The m', 'ost p', 'ronou', 'nced ', 'physi', 'ologi']
|
123
|
+
```
|
124
|
+
|
125
|
+
```python
|
126
|
+
ssplit(text, by="non_alphanumeric")
|
127
|
+
# ['The most pronounced physiological changes in sleep occur in the brain.[',
|
128
|
+
# '10',
|
129
|
+
# '] The brain uses significantly less energy during sleep than it does when awake, especially during non-REM sleep. In areas with reduced activity, the brain restores its supply of adenosine triphosphate (ATP), the molecule used for short-term storage and transport of energy.[',
|
130
|
+
# '11',
|
131
|
+
# '] In quiet waking, the brain is responsible for ',
|
132
|
+
# '20',
|
133
|
+
# "% of the body's energy use, thus this reduction has a noticeable effect on overall energy consumption.[",
|
134
|
+
# '12',
|
135
|
+
# ']']
|
136
|
+
```
|
137
|
+
|
138
|
+
```python
|
139
|
+
ssplit(text, by="sent")
|
140
|
+
#['The most pronounced physiological changes in sleep occur in the brain.',
|
141
|
+
#'[10] The brain uses significantly less energy during sleep than it does when awake, especially during non-REM sleep.',
|
142
|
+
#'In areas with reduced activity, the brain restores its supply of adenosine triphosphate (ATP), the molecule used for short-term storage and transport of energy.',
|
143
|
+
#"[11] In quiet waking, the brain is responsible for 20% of the body's energy use, thus this reduction has a noticeable effect on overall energy consumption.",
|
144
|
+
#'[12]']
|
145
|
+
```
|
146
|
+
|
147
|
+
```python
|
148
|
+
ssplit(text, by="lowup")
|
149
|
+
# ["The most pronounced physiological changes in sleep occur in the brain.[10] The brain uses significantly less energy during sleep than it does when awake, especially during non-REM sleep. In areas with reduced activity, the brain restores its supply of adenosine triphosphate (ATP), the molecule used for short-term storage and transport of energy.[11] In quiet waking, the brain is responsible for 20% of the body's energy use, thus this reduction has a noticeable effect on overall energy consumption.[12]"]
|
150
|
+
|
151
|
+
```
|
152
|
+
|
153
|
+
|
154
|
+
|
155
|
+
### stats
|
156
|
+
|
157
|
+
#### **FuncCmpt** ( two groups cmp)
|
158
|
+
|
159
|
+
```python
|
160
|
+
FuncCmpt(X1, X2, pmc='auto', pair='unpaired')
|
161
|
+
```
|
162
|
+
|
163
|
+
#### FuncMultiCmpt ( multiple groups cmp)
|
164
|
+
|
165
|
+
```python
|
166
|
+
FuncMultiCmpt(pmc='pmc', pair='unpair', data=None, dv=None, factor=None,
|
167
|
+
ss_type=2, detailed=True, effsize='np2',
|
168
|
+
correction='auto', between=None, within=None,
|
169
|
+
subject=None, group=None
|
170
|
+
)
|
171
|
+
```
|
172
|
+
|
173
|
+
|
174
|
+
|
175
|
+
#### FuncStars
|
176
|
+
|
177
|
+
```python
|
178
|
+
FuncStars(ax,
|
179
|
+
pval=None,
|
180
|
+
Ylim=None,
|
181
|
+
Xlim=None,
|
182
|
+
symbol='*',
|
183
|
+
yscale=0.95,
|
184
|
+
x1=0,
|
185
|
+
x2=1,
|
186
|
+
alpha=0.05,
|
187
|
+
fontsize=14,
|
188
|
+
fontsize_note=6,
|
189
|
+
rotation=0,
|
190
|
+
fontname='Arial',
|
191
|
+
values_below=None,
|
192
|
+
linego=True,
|
193
|
+
linestyle='-',
|
194
|
+
linecolor='k',
|
195
|
+
linewidth=.8,
|
196
|
+
nsshow='off',
|
197
|
+
symbolcolor='k',
|
198
|
+
tailindicator=[0.06, 0.06],
|
199
|
+
report=None,
|
200
|
+
report_scale=-0.1,
|
201
|
+
report_loc=None)
|
202
|
+
```
|
203
|
+
|
204
|
+
### plots
|
205
|
+
|
206
|
+
#### stdshade
|
207
|
+
|
208
|
+
```python
|
209
|
+
stdshade(ax=None,*args, **kwargs)
|
210
|
+
```
|
211
|
+
|
212
|
+
#### add_colorbar
|
213
|
+
|
214
|
+
```python
|
215
|
+
add_colorbar(im, width=None, pad=None, **kwargs)
|
216
|
+
```
|
217
|
+
|
218
|
+
#### get_color
|
219
|
+
|
220
|
+
```python
|
221
|
+
get_color(n=1, cmap='auto')
|
222
|
+
```
|
223
|
+
|
224
|
+
```python
|
225
|
+
get_color(12)
|
226
|
+
# ['#474747',
|
227
|
+
# '#FF2C00',
|
228
|
+
# '#0C5DA5',
|
229
|
+
# '#845B97',
|
230
|
+
# '#58BBCC',
|
231
|
+
# '#FF9500',
|
232
|
+
# '#D57DBE',
|
233
|
+
# '#474747',
|
234
|
+
# '#FF2C00',
|
235
|
+
# '#0C5DA5',
|
236
|
+
# '#845B97',
|
237
|
+
# '#58BBCC']
|
238
|
+
```
|
239
|
+
|
240
|
+
|
241
|
+
|
242
|
+
#### img appearance
|
243
|
+
|
244
|
+
#### imgsets
|
245
|
+
|
246
|
+
```python
|
247
|
+
imgsets(
|
248
|
+
img,
|
249
|
+
sets=None,
|
250
|
+
show=True,
|
251
|
+
show_axis=False,
|
252
|
+
size=None,
|
253
|
+
dpi=100,
|
254
|
+
figsize=None,
|
255
|
+
auto=False,
|
256
|
+
filter_kws=None,
|
257
|
+
)
|
258
|
+
```
|
259
|
+
|
260
|
+
```python
|
261
|
+
img = imgsets(
|
262
|
+
fpath,
|
263
|
+
sets={"rota": -5, "sharp": 10},
|
264
|
+
dpi=200,
|
265
|
+
# show_axis=True,
|
266
|
+
)
|
267
|
+
figsave(dir_save, "test1_sharp.pdf")
|
268
|
+
|
269
|
+
|
270
|
+
img2 = imgsets(
|
271
|
+
fpath,
|
272
|
+
sets={"rota": -5, "crop": [100, 100, 300, 400], "sharp": 10},
|
273
|
+
dpi=200,
|
274
|
+
filter_kws={
|
275
|
+
"sharpen": 10,
|
276
|
+
},
|
277
|
+
# show_axis=True,
|
278
|
+
)
|
279
|
+
figsave(dir_save, "test2_crop.pdf")
|
280
|
+
```
|
281
|
+
|
282
|
+
```python
|
283
|
+
fload(dir_img)
|
284
|
+
```
|
285
|
+
|
286
|
+

|
287
|
+
|
288
|
+
```python
|
289
|
+
imgsets(img, sets={"color": 1.5}, show=0)
|
290
|
+
```
|
291
|
+
|
292
|
+

|
293
|
+
|
294
|
+
```python
|
295
|
+
imgsets(img, sets={"pad": (300, 300), "bgcolor": (73, 162, 127)}, show=0)
|
296
|
+
```
|
297
|
+
|
298
|
+

|
299
|
+
|
300
|
+
```python
|
301
|
+
imgsets(
|
302
|
+
img,
|
303
|
+
sets={"contrast": 1.3, "color": 1.5, "pad": (300, 300)},
|
304
|
+
show=0,
|
305
|
+
filter_kws=dict(sh=1050, EDG=10, gaus=5),
|
306
|
+
)
|
307
|
+
```
|
308
|
+
|
309
|
+

|
310
|
+
|
311
|
+
```python
|
312
|
+
imgsets(
|
313
|
+
img,
|
314
|
+
sets={"color": 10.5},
|
315
|
+
show=0,
|
316
|
+
filter_kws=dict(EDGE_ENHANCE=50, EDGE_NHANCEmore=50),
|
317
|
+
)
|
318
|
+
```
|
319
|
+
|
320
|
+

|
321
|
+
|
322
|
+
```python
|
323
|
+
imgsets(
|
324
|
+
img,
|
325
|
+
sets=dict(contr=1.5, rm="default"),
|
326
|
+
show=0,
|
327
|
+
# filter_kws=dict(sharp=1),
|
328
|
+
)
|
329
|
+
```
|
330
|
+
|
331
|
+

|
332
|
+
|
333
|
+
```python
|
334
|
+
imgsets(
|
335
|
+
img,
|
336
|
+
sets=dict(contr=0, rm="default"),
|
337
|
+
show=0,
|
338
|
+
filter_kws=dict(sharp=1),
|
339
|
+
)
|
340
|
+
```
|
341
|
+
|
342
|
+

|
343
|
+
|
344
|
+
#### figsets
|
345
|
+
|
346
|
+
```python
|
347
|
+
figsets(*args)
|
348
|
+
```
|
349
|
+
|
350
|
+
```python
|
351
|
+
cm = 1 / 2.54
|
352
|
+
# plt.style.use("paper")
|
353
|
+
plt.figure(figsize=[8 * cm, 5 * cm])
|
354
|
+
for i in range(2, 4):
|
355
|
+
plt.plot(x, y * i, ls="-")
|
356
|
+
figsets(
|
357
|
+
plt.gca(),
|
358
|
+
{
|
359
|
+
"xlabel": f"time([{x[0]}:{x[-1]}])",
|
360
|
+
"ylabel": "Amplitude (signals)",
|
361
|
+
# "titel": "paper",
|
362
|
+
"xlim": [0, 600],
|
363
|
+
"xtick": np.arange(0, 620, 150),
|
364
|
+
"xlabel": "test xticklabel",
|
365
|
+
# "ylim": [-2.5, 2.5],
|
366
|
+
"sp": "go",
|
367
|
+
# "style": "paper",
|
368
|
+
"box": ":",
|
369
|
+
"grid": "on",
|
370
|
+
"minorticks": "on",
|
371
|
+
"ticks": {"c": "k"},
|
372
|
+
},
|
373
|
+
)
|
374
|
+
figsets('style','paper')
|
375
|
+
```
|
376
|
+
|
377
|
+
```python
|
378
|
+
cm = 1/2.54 # centimeters in inches
|
379
|
+
fig, ax = plt.subplots(1, 1, figsize=(7*cm, 5*cm))
|
380
|
+
x = np.linspace(0, 2 * np.pi, 50) * 100
|
381
|
+
y = np.sin(x)
|
382
|
+
c=get_color(7)
|
383
|
+
|
384
|
+
for i in range(2,7):
|
385
|
+
plt.plot(x, y*i,c=c[i])
|
386
|
+
figsets(
|
387
|
+
ax,
|
388
|
+
{
|
389
|
+
"xlim": [0, 450],
|
390
|
+
# "ylim": [-1.5, 1.5],
|
391
|
+
"xlabel": "2222",
|
392
|
+
# "style":"paper",
|
393
|
+
"yticks": np.arange(-5,5, 2),
|
394
|
+
"ylabel": "ylabelsssss",
|
395
|
+
"xtkbel": range(0, 800, 100),
|
396
|
+
# "spine": 5,
|
397
|
+
"suptitle": "supertitle",
|
398
|
+
# "minorticks": "y",
|
399
|
+
# "ticksloc":"lt",
|
400
|
+
# "ticks": {"direction": "out",'c':'b'},
|
401
|
+
"rotation":45,
|
402
|
+
# 'box':"lt",
|
403
|
+
# "labellocation":'r',
|
404
|
+
# "ax_color":'b',
|
405
|
+
# 'grid':{"which":'minor','lw':1,"ls":'-.','c':'b','al':0.3},
|
406
|
+
},
|
407
|
+
)
|
408
|
+
```
|
409
|
+
|
py2ls/__init__.py
ADDED
py2ls/brain_atlas.py
ADDED
@@ -0,0 +1,145 @@
|
|
1
|
+
import requests
|
2
|
+
from PIL import Image
|
3
|
+
from io import BytesIO
|
4
|
+
import os
|
5
|
+
|
6
|
+
|
7
|
+
def atlas_url(ml, ap, dv, kind="rat"):
|
8
|
+
"""
|
9
|
+
Constructs the URL for the rat or mouse brain atlas API based on the provided coordinates.
|
10
|
+
In neuroscience, ML, AP, and DV coordinates are commonly used to specify locations within
|
11
|
+
the brain. Here's what they stand for:
|
12
|
+
|
13
|
+
Args:
|
14
|
+
ML(float): Medio-lateral coordinate. It refers to the position along the medial-lateral axis of
|
15
|
+
the brain. The medio-lateral axis runs from the midline (medial) to the sides
|
16
|
+
(lateral) of the brain.
|
17
|
+
AP(float): Antero-posterior coordinate. It refers to the position along the anterior-posterior
|
18
|
+
axis of the brain. The anterior-posterior axis runs from the front (anterior) to the
|
19
|
+
back (posterior) of the brain.
|
20
|
+
DV(float): Dorso-ventral coordinate. It refers to the position along the dorso-ventral axis of
|
21
|
+
the brain. The dorso-ventral axis runs from the top (dorsal) to the bottom (ventral)
|
22
|
+
of the brain.
|
23
|
+
Returns:
|
24
|
+
str: The constructed URL.
|
25
|
+
"""
|
26
|
+
if "ra" in kind.lower():
|
27
|
+
api = "http://labs.gaidi.ca/rat-brain-atlas/api.php?"
|
28
|
+
print(f"check the url: {api[:-8]}?ml={ml}&ap={ap}&dv={dv}")
|
29
|
+
elif "mo" in kind.lower() or "mi" in kind.lower():
|
30
|
+
api = "https://labs.gaidi.ca/mouse-brain-atlas/?"
|
31
|
+
return f"{api}ml={ml}&ap={ap}&dv={dv}"
|
32
|
+
|
33
|
+
|
34
|
+
def get_3fpath(dir_save, ml, ap, dv):
|
35
|
+
"""
|
36
|
+
Generates a filename based on the provided coordinates and directory.
|
37
|
+
|
38
|
+
Args:
|
39
|
+
dir_save (str): The directory where the file will be saved.
|
40
|
+
ml (float): The ML coordinate.
|
41
|
+
ap (float): The AP coordinate.
|
42
|
+
dv (float): The DV coordinate.
|
43
|
+
|
44
|
+
Returns:
|
45
|
+
str: The generated filename.
|
46
|
+
"""
|
47
|
+
filename, file_extension = os.path.splitext(dir_save)
|
48
|
+
if file_extension == "":
|
49
|
+
filename += f"brainatlas_ml={ml}&ap={ap}&dv={dv}"
|
50
|
+
return filename
|
51
|
+
|
52
|
+
|
53
|
+
def download_image(image_url, color_mode=True):
|
54
|
+
"""
|
55
|
+
Downloads an image from a given URL and converts it to RGB mode if required.
|
56
|
+
|
57
|
+
Args:
|
58
|
+
image_url (str): The URL of the image to download.
|
59
|
+
color_mode (bool, optional): Whether to convert the image to RGB mode. Defaults to True.
|
60
|
+
|
61
|
+
Returns:
|
62
|
+
PIL.Image: The downloaded image.
|
63
|
+
"""
|
64
|
+
try:
|
65
|
+
# Download the image from the specified URL
|
66
|
+
response = requests.get(image_url)
|
67
|
+
|
68
|
+
# Check if the response status code is OK (200)
|
69
|
+
response.raise_for_status()
|
70
|
+
image = Image.open(BytesIO(response.content))
|
71
|
+
if color_mode:
|
72
|
+
image = image.convert("RGB")
|
73
|
+
return image
|
74
|
+
except requests.exceptions.RequestException as e:
|
75
|
+
print(f"Error: Unable to download image from {image_url}")
|
76
|
+
print(e)
|
77
|
+
return None
|
78
|
+
|
79
|
+
|
80
|
+
def brain_atlas(ml, ap, dv, kind="rat", dir_save=None, pdf_filename=None):
|
81
|
+
"""
|
82
|
+
Retrieves images of the rat or mouse brain atlas for the specified coordinates.
|
83
|
+
|
84
|
+
Args:
|
85
|
+
ml (float): The ML coordinate.
|
86
|
+
ap (float): The AP coordinate.
|
87
|
+
dv (float): The DV coordinate.
|
88
|
+
kind (str, optional): The type of brain atlas ('rat' or 'mouse'). Defaults to 'rat'.
|
89
|
+
dir_save (str, optional): The directory where the images will be saved. Defaults to None.
|
90
|
+
|
91
|
+
Returns:
|
92
|
+
tuple: A tuple containing PIL images of coronal, sagittal, and horizontal views, respectively.
|
93
|
+
|
94
|
+
Note:
|
95
|
+
The images are also saved as PDF files in the specified directory if `dir_save` is provided.
|
96
|
+
"""
|
97
|
+
# Construct the URL for the rat brain atlas API based on the provided coordinates
|
98
|
+
url = atlas_url(ml, ap, dv, kind=kind)
|
99
|
+
try:
|
100
|
+
response = requests.get(url)
|
101
|
+
response.raise_for_status()
|
102
|
+
data = response.json()
|
103
|
+
|
104
|
+
# Download and process the images from the URLs provided in the JSON data
|
105
|
+
coronal_image = download_image(data["coronal"]["image_url"], color_mode=True)
|
106
|
+
sagittal_image = download_image(data["sagittal"]["image_url"], color_mode=True)
|
107
|
+
horizontal_image = download_image(
|
108
|
+
data["horizontal"]["image_url"], color_mode=True
|
109
|
+
)
|
110
|
+
|
111
|
+
# Check if all images were successfully downloaded
|
112
|
+
if coronal_image and sagittal_image and horizontal_image:
|
113
|
+
if dir_save:
|
114
|
+
# Construct filename with kind suffix
|
115
|
+
filename = get_3fpath(dir_save, ml, ap, dv)
|
116
|
+
coronal_image.save(filename + f"_{kind}_coronal.pdf")
|
117
|
+
sagittal_image.save(filename + f"_{kind}_sagittal.pdf")
|
118
|
+
horizontal_image.save(filename + f"_{kind}_horizontal.pdf")
|
119
|
+
return (coronal_image, sagittal_image, horizontal_image)
|
120
|
+
else:
|
121
|
+
print("Error: Unable to download images.")
|
122
|
+
return None
|
123
|
+
except requests.exceptions.RequestException as e:
|
124
|
+
print(f"Error: Unable to complete web request\n{url}.")
|
125
|
+
print(e)
|
126
|
+
return None
|
127
|
+
|
128
|
+
|
129
|
+
# # Example usage:
|
130
|
+
# ml = 8.64
|
131
|
+
# ap = -0.36
|
132
|
+
# dv = 7.0
|
133
|
+
|
134
|
+
# # Retrieve the rat brain atlas images for the specified coordinates
|
135
|
+
# S = brain_atlas(
|
136
|
+
# ml, ap, dv, dir_save="/Users/macjianfeng/Dropbox/Downloads/", kind="rat"
|
137
|
+
# )
|
138
|
+
|
139
|
+
# if S:
|
140
|
+
# # Display or further process the retrieved images
|
141
|
+
# coronal_image = S["coronal"]
|
142
|
+
# sagittal_image = S["sagittal"]
|
143
|
+
# horizontal_image = S["horizontal"]
|
144
|
+
# # coronal_image.show() # Display the coronal image
|
145
|
+
# # Similarly, you can display or process sagittal and horizontal images
|