Skip to content
GitLab
Explore
Sign in
Primary navigation
Search or go to…
Project
R
ruby
Manage
Activity
Members
Labels
Plan
Issues
Issue boards
Milestones
Code
Merge requests
Repository
Branches
Commits
Tags
Repository graph
Compare revisions
Build
Pipelines
Jobs
Pipeline schedules
Artifacts
Deploy
Releases
Package registry
Model registry
Operate
Environments
Terraform modules
Monitor
Incidents
Analyze
Value stream analytics
Contributor analytics
CI/CD analytics
Repository analytics
Model experiments
Help
Help
Support
GitLab documentation
Compare GitLab plans
Community forum
Contribute to GitLab
Provide feedback
Keyboard shortcuts
?
Snippets
Groups
Projects
Show more breadcrumbs
catalog
ruby
Commits
a11c6cea
Commit
a11c6cea
authored
3 months ago
by
Florian Ziemen
Browse files
Options
Downloads
Patches
Plain Diff
processing script
parent
072c62b9
No related branches found
Branches containing commit
No related tags found
Tags containing commit
No related merge requests found
Changes
1
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
processing/create_yaml.ipynb
+166
-0
166 additions, 0 deletions
processing/create_yaml.ipynb
with
166 additions
and
0 deletions
processing/create_yaml.ipynb
0 → 100644
+
166
−
0
View file @
a11c6cea
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import yaml\n",
"import pandas as pd\n",
"from pathlib import Path\n",
"import re\n",
"import logging\n",
"from typing import Union\n",
"import xarray as xr\n",
"import warnings"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"logging.basicConfig()\n",
"logger = logging.getLogger(\"catalog_netcdf\")\n",
"logger.setLevel(logging.INFO)\n",
"\n",
"warnings.filterwarnings(\"ignore\", category=xr.SerializationWarning)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"def process_table_file (table_file: Path):\n",
" df = read_table(table_file=table_file, )\n",
" table_dir = Path (\"../catalog\") / table_file.stem\n",
" table_dir.mkdir(exist_ok=True)\n",
" catalog = process_table(df, table_dir)\n",
" \n",
" with open (table_dir/Path(\"main.yaml\"), 'w') as outfile:\n",
" yaml.dump(catalog, outfile)\n",
"\n",
"def read_table(table_file: Path) -> pd.DataFrame:\n",
" names = ['garbage1', 'simulation_id' , \"experiment\", \"resolution\", 'start_date', 'end_date', 'path', 'contact', 'garbage2']\n",
" usecols = [ x for x in names if 'garbage' not in x]\n",
" converters = { x : lambda s: s.strip() for x in usecols if \"date not in x\"}\n",
" df = pd.read_csv(table_file, delimiter = '|', names = names , usecols=usecols, header=1, converters=converters)\n",
" df.iloc[:,0] = df.iloc[:,0].str.replace(\"\\\\_\", \"_\").str.strip()\n",
" df.iloc[:,-2] = df.iloc[:,-2].str.replace(\"\\\\_\", \"_\").str.strip()\n",
" df[\"path\"] = [Path(x) for x in df[\"path\"]]\n",
" logger.debug(df)\n",
" return df \n",
"\n",
"def process_table(df: pd.DataFrame, table_dir: Path) -> dict:\n",
" catalog = dict (sources = dict())\n",
" \n",
" for _, row in df.iterrows():\n",
" catalog['sources'] [row['simulation_id'] ]= create_entry (row, table_dir=table_dir)\n",
" return catalog"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"def create_entry ( experiment, table_dir: Path) :\n",
" entry_filename = table_dir / Path (f\"{experiment['simulation_id']}.yaml\")\n",
" entry_content = {'sources' : dict()}\n",
" filegroups = analyze_dataset(experiment['simulation_id'], experiment['path'])\n",
" for filegroup, files in filegroups.items():\n",
" entry_content['sources'][filegroup] = create_stream (experiment, filegroup, files)\n",
" with open (entry_filename, 'w') as outfile:\n",
" yaml.dump(entry_content, outfile)\n",
"\n",
" return dict ( driver = \"yaml_file_cat\", description= experiment[\"experiment\"], args = dict (path = \"{{CATALOG_DIR}}/\" + f'{experiment[\"simulation_id\"]}.yaml'))\n",
"\n",
"def analyze_dataset (id, input_dir: Path):\n",
" files = gen_files(id, input_dir)\n",
" id, parts = split_filenamens(id, files)\n",
" patterns = get_patterns(parts)\n",
" logger.debug(f\"{id=} {patterns=}\")\n",
" filelist = gen_filelist(input_dir, id, patterns)\n",
" return filelist\n",
"\n",
"def gen_files(id, input_dir):\n",
" files = [str (x) for x in input_dir.glob(f\"{id}*.nc\")]\n",
" files = [ x for x in files if \"restart\" not in x]\n",
" return [ Path(x) for x in files ]\n",
"\n",
"\n",
"def split_filenamens(id, files):\n",
" stems = list (f.stem for f in files)\n",
" parts = [ x[len(id):]for x in stems]\n",
" return id, parts\n",
"\n",
"def gen_filelist (input_dir, id, patterns):\n",
" return { pattern : list (input_dir.glob (f\"{id}*{pattern}*.nc\")) for pattern in patterns}\n",
"\n",
"\n",
"def get_patterns (parts):\n",
" patterns = { re.sub(r'\\d{4}-\\d{2}-\\d{2}_', \"\", x ) for x in parts} # r'\\\\d\\{4\\}-\\\\d\\{2\\}-\\\\d\\{2\\}'\n",
" patterns = { re.sub(r'\\d{8}T\\d{6}Z', \"\", x) for x in patterns} # r'\\\\d\\{8\\}T\\\\d\\{6\\}Z'\n",
" patterns = { re.sub (r'^_', '', x) for x in patterns }\n",
" patterns = { re.sub (r'_$', '', x) for x in patterns }\n",
" return patterns\n",
"\n",
"def create_stream (experiment, filegroup, files):\n",
" stream = dict (driver = \"netcdf\")\n",
" stream [ \"args\" ] = dict (chunks = dict ( time= 1), xarray_kwargs = dict (use_cftime = True), urlpath = [ str(x) for x in files])\n",
" stream [ \"metadata\"] = { k : v.strip() for k,v in experiment.items() if k != \"path\" }\n",
" stream [\"metadata\"] |= get_variable_metadata(files)\n",
" return stream\n",
"\n",
"def get_variable_metadata(files):\n",
" ds = xr.open_dataset(files[0])\n",
" variables = sorted ( x for x in ds)\n",
" long_names = [ ds[x].attrs.get(\"long_name\", x) for x in variables]\n",
" return dict (variables = variables, variable_long_names = long_names)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"table_files = sorted(Path(\"../inputs\").glob(\"*.md\"))\n",
"main_cat = dict (sources = dict())\n",
"for table_file in table_files:\n",
" table = table_file.stem\n",
" process_table_file(table_file)\n",
" main_cat [\"sources\"][table] = dict ( driver = \"yaml_file_cat\", args = dict (path = \"{{CATALOG_DIR}}/\" + f\"{table}/main.yaml\"))\n",
"\n",
" with open (Path (\"../catalog/main.yaml\"), 'w') as outfile:\n",
" yaml.dump(main_cat, outfile)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "py_312",
"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.12.5"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
%% Cell type:code id: tags:
```
python
import
yaml
import
pandas
as
pd
from
pathlib
import
Path
import
re
import
logging
from
typing
import
Union
import
xarray
as
xr
import
warnings
```
%% Cell type:code id: tags:
```
python
logging
.
basicConfig
()
logger
=
logging
.
getLogger
(
"
catalog_netcdf
"
)
logger
.
setLevel
(
logging
.
INFO
)
warnings
.
filterwarnings
(
"
ignore
"
,
category
=
xr
.
SerializationWarning
)
```
%% Cell type:code id: tags:
```
python
def
process_table_file
(
table_file
:
Path
):
df
=
read_table
(
table_file
=
table_file
,
)
table_dir
=
Path
(
"
../catalog
"
)
/
table_file
.
stem
table_dir
.
mkdir
(
exist_ok
=
True
)
catalog
=
process_table
(
df
,
table_dir
)
with
open
(
table_dir
/
Path
(
"
main.yaml
"
),
'
w
'
)
as
outfile
:
yaml
.
dump
(
catalog
,
outfile
)
def
read_table
(
table_file
:
Path
)
->
pd
.
DataFrame
:
names
=
[
'
garbage1
'
,
'
simulation_id
'
,
"
experiment
"
,
"
resolution
"
,
'
start_date
'
,
'
end_date
'
,
'
path
'
,
'
contact
'
,
'
garbage2
'
]
usecols
=
[
x
for
x
in
names
if
'
garbage
'
not
in
x
]
converters
=
{
x
:
lambda
s
:
s
.
strip
()
for
x
in
usecols
if
"
date not in x
"
}
df
=
pd
.
read_csv
(
table_file
,
delimiter
=
'
|
'
,
names
=
names
,
usecols
=
usecols
,
header
=
1
,
converters
=
converters
)
df
.
iloc
[:,
0
]
=
df
.
iloc
[:,
0
].
str
.
replace
(
"
\\
_
"
,
"
_
"
).
str
.
strip
()
df
.
iloc
[:,
-
2
]
=
df
.
iloc
[:,
-
2
].
str
.
replace
(
"
\\
_
"
,
"
_
"
).
str
.
strip
()
df
[
"
path
"
]
=
[
Path
(
x
)
for
x
in
df
[
"
path
"
]]
logger
.
debug
(
df
)
return
df
def
process_table
(
df
:
pd
.
DataFrame
,
table_dir
:
Path
)
->
dict
:
catalog
=
dict
(
sources
=
dict
())
for
_
,
row
in
df
.
iterrows
():
catalog
[
'
sources
'
]
[
row
[
'
simulation_id
'
]
]
=
create_entry
(
row
,
table_dir
=
table_dir
)
return
catalog
```
%% Cell type:code id: tags:
```
python
def
create_entry
(
experiment
,
table_dir
:
Path
)
:
entry_filename
=
table_dir
/
Path
(
f
"
{
experiment
[
'
simulation_id
'
]
}
.yaml
"
)
entry_content
=
{
'
sources
'
:
dict
()}
filegroups
=
analyze_dataset
(
experiment
[
'
simulation_id
'
],
experiment
[
'
path
'
])
for
filegroup
,
files
in
filegroups
.
items
():
entry_content
[
'
sources
'
][
filegroup
]
=
create_stream
(
experiment
,
filegroup
,
files
)
with
open
(
entry_filename
,
'
w
'
)
as
outfile
:
yaml
.
dump
(
entry_content
,
outfile
)
return
dict
(
driver
=
"
yaml_file_cat
"
,
description
=
experiment
[
"
experiment
"
],
args
=
dict
(
path
=
"
{{CATALOG_DIR}}/
"
+
f
'
{
experiment
[
"
simulation_id
"
]
}
.yaml
'
))
def
analyze_dataset
(
id
,
input_dir
:
Path
):
files
=
gen_files
(
id
,
input_dir
)
id
,
parts
=
split_filenamens
(
id
,
files
)
patterns
=
get_patterns
(
parts
)
logger
.
debug
(
f
"
{
id
=
}
{
patterns
=
}
"
)
filelist
=
gen_filelist
(
input_dir
,
id
,
patterns
)
return
filelist
def
gen_files
(
id
,
input_dir
):
files
=
[
str
(
x
)
for
x
in
input_dir
.
glob
(
f
"
{
id
}
*.nc
"
)]
files
=
[
x
for
x
in
files
if
"
restart
"
not
in
x
]
return
[
Path
(
x
)
for
x
in
files
]
def
split_filenamens
(
id
,
files
):
stems
=
list
(
f
.
stem
for
f
in
files
)
parts
=
[
x
[
len
(
id
):]
for
x
in
stems
]
return
id
,
parts
def
gen_filelist
(
input_dir
,
id
,
patterns
):
return
{
pattern
:
list
(
input_dir
.
glob
(
f
"
{
id
}
*
{
pattern
}
*.nc
"
))
for
pattern
in
patterns
}
def
get_patterns
(
parts
):
patterns
=
{
re
.
sub
(
r
'
\d{4}-\d{2}-\d{2}_
'
,
""
,
x
)
for
x
in
parts
}
# r'\\d\{4\}-\\d\{2\}-\\d\{2\}'
patterns
=
{
re
.
sub
(
r
'
\d{8}T\d{6}Z
'
,
""
,
x
)
for
x
in
patterns
}
# r'\\d\{8\}T\\d\{6\}Z'
patterns
=
{
re
.
sub
(
r
'
^_
'
,
''
,
x
)
for
x
in
patterns
}
patterns
=
{
re
.
sub
(
r
'
_$
'
,
''
,
x
)
for
x
in
patterns
}
return
patterns
def
create_stream
(
experiment
,
filegroup
,
files
):
stream
=
dict
(
driver
=
"
netcdf
"
)
stream
[
"
args
"
]
=
dict
(
chunks
=
dict
(
time
=
1
),
xarray_kwargs
=
dict
(
use_cftime
=
True
),
urlpath
=
[
str
(
x
)
for
x
in
files
])
stream
[
"
metadata
"
]
=
{
k
:
v
.
strip
()
for
k
,
v
in
experiment
.
items
()
if
k
!=
"
path
"
}
stream
[
"
metadata
"
]
|=
get_variable_metadata
(
files
)
return
stream
def
get_variable_metadata
(
files
):
ds
=
xr
.
open_dataset
(
files
[
0
])
variables
=
sorted
(
x
for
x
in
ds
)
long_names
=
[
ds
[
x
].
attrs
.
get
(
"
long_name
"
,
x
)
for
x
in
variables
]
return
dict
(
variables
=
variables
,
variable_long_names
=
long_names
)
```
%% Cell type:code id: tags:
```
python
table_files
=
sorted
(
Path
(
"
../inputs
"
).
glob
(
"
*.md
"
))
main_cat
=
dict
(
sources
=
dict
())
for
table_file
in
table_files
:
table
=
table_file
.
stem
process_table_file
(
table_file
)
main_cat
[
"
sources
"
][
table
]
=
dict
(
driver
=
"
yaml_file_cat
"
,
args
=
dict
(
path
=
"
{{CATALOG_DIR}}/
"
+
f
"
{
table
}
/main.yaml
"
))
with
open
(
Path
(
"
../catalog/main.yaml
"
),
'
w
'
)
as
outfile
:
yaml
.
dump
(
main_cat
,
outfile
)
```
This diff is collapsed.
Click to expand it.
Preview
0%
Loading
Try again
or
attach a new file
.
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Save comment
Cancel
Please
register
or
sign in
to comment