Compare commits

..

5 Commits

Author SHA256 Message Date
ee96100a73 uses dotenv to store api key and other important variables
if a value is not found in .env it will be prompted, but not checked
next step is user docs
2026-05-13 12:31:26 +02:00
686f869d10 documents all the functions/classes/methods (by hand)
no AI used, it took more than I'm willing to admit but it's done
2026-05-13 12:12:32 +02:00
2eea3fc2dd ignores output/attachments 2026-05-13 10:27:40 +02:00
cbf5cdd115 clears comments 2026-05-13 10:26:15 +02:00
a6d4c72f9c adds dependency: dotenv 2026-05-13 09:53:57 +02:00
9 changed files with 215 additions and 75989 deletions

1
.gitignore vendored
View File

@@ -5,6 +5,7 @@
output/*.json
output/*.h5
output/*.nxs
output/attachments/*.*
# ---> Python
# Byte-compiled / optimized / DLL files

Binary file not shown.

Before

Width:  |  Height:  |  Size: 301 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 301 KiB

File diff suppressed because it is too large Load Diff

View File

@@ -3,3 +3,4 @@ asyncio
h5py
pillow
elabapi_python
dotenv

View File

@@ -1,4 +1,5 @@
import os, requests
from dotenv import load_dotenv
from getpass import getpass
import elabapi_python as elabapi
@@ -11,19 +12,22 @@ class APIHandler:
(since the API doesn't support downloading attachments AFAIK).
Args:
api_key: A valid API key for the eLabFTW instance where the data is stored, with permissions to access the relevant entries.
eLabFTW's API keys are well documented here: https://doc.elabftw.net/docs/usage/api/.
If you don't have an API key and are uncapable of creating one, contact your eLabFTW administrator.
Or RTFM and create one yourself, it's not that hard.
ELABFTW_API_URL: Complete URL of the eLabFTW instance's root for the API endpoints.
In full caps because it won't (shouldn't) be changed much.
api_key: str: A valid API key for the eLabFTW instance where the data is stored, with permissions to access the relevant entries.
eLabFTW's API keys are well documented here: https://doc.elabftw.net/docs/usage/api/.
If you don't have an API key and are uncapable of creating one, contact your eLabFTW administrator.
Or RTFM and create one yourself, it's not that hard.
ELABFTW_API_URL: str: Complete URL of the eLabFTW instance's root for the API endpoints.
In full caps because it won't (shouldn't) be changed much.
"""
# TO-DO: remove static url.
def __init__(
self, api_key="", ELABFTW_API_URL="https://elabftw.fisica.unina.it/api/v2"
):
"""Init method, apikey suggested but not required (empty by default)."""
def __init__(self, api_key="", ELABFTW_API_URL=None):
"""Init method, api_key suggested but not required (empty by default)."""
if not ELABFTW_API_URL:
load_dotenv()
ELABFTW_API_URL = os.getenv("ELABFTW_API_URL") or input(
"Enter a valid eLabFTW API URL (ends with '/api/v2)': "
)
self.api_key = api_key
self.auth = {"Authorization": api_key}
self.content = {"Content-Type": "application/json"}
@@ -34,9 +38,9 @@ class APIHandler:
"""
Returns raw data (as dictionary) from its elabid and entry type.
args:
elabid: elabftw internal id of the selected resource.
entryType: Resource type. Anything other than "experiments" or "items" WILL raise an error.
Args:
elabid: int: elabftw internal id of the selected resource.
entryType: str: Resource type. Anything other than "experiments" or "items" WILL raise an error.
"""
if entryType not in ["experiments", "items"]:
raise Exception(
@@ -91,9 +95,9 @@ class APIHandler:
* The value is the attachment's binary data.
Args:
elabid: eLabFTW internal ID of the selected resource.
upload_id: eLabFTW internal ID of the selected upload.
entryType: Resource type. Anything other than "experiments" or "items" WILL raise an error.
elabid: int: eLabFTW internal ID of the selected resource.
upload_id: int: eLabFTW internal ID of the selected upload.
entryType: str: Resource type. Anything other than "experiments" or "items" WILL raise an error.
"""
if entryType not in ["experiments", "items"]:
raise Exception(
@@ -136,12 +140,12 @@ class APIHandler:
Returns full path of the output file.
Args:
elabid: eLabFTW internal ID of the selected resource.
upload_id: eLabFTW internal ID of the selected upload.
entryType: Resource type. Anything other than "experiments" or "items" WILL raise an error.
dump_dir: Directory to which to save the attachments. Default is "output/attachments".
persistent: [Unused] Decides if the files will stay on disk after all operations are completed.
If set to False, deletes the file upon exiting.
elabid: int: eLabFTW internal ID of the selected resource.
upload_id: int: eLabFTW internal ID of the selected upload.
entryType: str: Resource type. Anything other than "experiments" or "items" WILL raise an error.
dump_dir: str: Directory to which to save the attachments. Default is "output/attachments".
persistent: bool: [Unused] Decides if the files will stay on disk after all operations are completed.
If set to False, deletes the file upon exiting. Default = True.
"""
if entryType not in ["experiments", "items"]:

View File

@@ -15,6 +15,10 @@ class Layer:
"""
def __init__(self, layer_data):
"""
Properties/Attributes:
Too many to list.
"""
try:
self.elabid = layer_data["id"]
self.operator = layer_data["fullname"]
@@ -131,6 +135,20 @@ class Layer:
self.description = layer_data.get("body") or None
def get_instruments(self, api_key):
"""
Retruns a dictionary of all the instruments used to create the layer.
The format of the dictionary is:
{
"laser_system": str,
"deposition_chamber": str,
"rheed_system": str
}
Arg: api_key: str: A valid API key for the eLabFTW instance where the data is stored, with permissions to access the relevant entries.
eLabFTW's API keys are well documented here: https://doc.elabftw.net/docs/usage/api/.
If you don't have an API key and are uncapable of creating one, contact your eLabFTW administrator.
Or RTFM and create one yourself, it's not that hard.
"""
raw_lasersys_data = APIHandler(api_key).get_entry_from_elabid(
self.laser_system_elabid, entryType="items"
)
@@ -220,6 +238,15 @@ class Entrypoint:
"""
def __init__(self, sample_data):
"""
Properties/Attributes:
* name: str: Name of the sample. Fairly important, and always present unless someone screws up REALLY bad.
* linked_items: dict: Dictionary generated by eLabFTW containing metadata on the items linked to the entrypoint.
* batch_elabid: int: eLabFTW internal id of the batch of the substrate used as the foundation of the sample.
* proposal: int: eLabFTW internal id of the proposal linked to the sample.
* linked_experiments: dict: Dictionary generated by eLabFTW containing metadata on the experiments linked to the entrypoint.
* linked_experiments_elabid: list: List of eLabFTW internal id's of the experiments linked to the entrypoint.
"""
try:
self.extra = sample_data["metadata_decoded"]["extra_fields"]
self.linked_items = sample_data["items_links"] # dict
@@ -239,6 +266,7 @@ class Entrypoint:
self.name = (
sample_data.get("title") or None
) # error prevention is more important than preventing empty fields here
# although I don't think it's even possible to fuck up this bad...
class Material:
@@ -254,6 +282,14 @@ class Material:
"""
def __init__(self, material_data):
"""
Properties/Attributes:
* name: str: Name of the material.
* compound_elabid: int: eLabFTW internal id of the compound.
* dimensions: str: Dimensions of the material, in standard format.
The class recognizes the unit of measurement and acts consequently.
* dimensions_unit: str: Unit of measurement - either "mm x mm", "inches" or None.
"""
try:
self.name = material_data["title"] # required
self.extra = material_data["metadata_decoded"]["extra_fields"]
@@ -275,6 +311,20 @@ class Material:
)
def get_compound_data(self, apikey):
"""
Returns a dictionary with the relevant data on the compound of which the material is made.
The format of the dictionary is:
{
"name": str,
"chemical_formula": str,
"cas_number": str
}
Arg: api_key: str: A valid API key for the eLabFTW instance where the data is stored, with permissions to access the relevant entries.
eLabFTW's API keys are well documented here: https://doc.elabftw.net/docs/usage/api/.
If you don't have an API key and are uncapable of creating one, contact your eLabFTW administrator.
Or RTFM and create one yourself, it's not that hard.
"""
raw_compound_data = APIHandler(apikey).get_entry_from_elabid(
self.compound_elabid, entryType="items"
)
@@ -295,7 +345,32 @@ class Material:
class Substrate(Material):
"""
Substrate(material_data) - where material_data is a Python dictionary.
Inherits from Material and it's meant to be used exclusively for eLabFTW Resources of the "Substrate" category.
"""
def __init__(self, material_data):
"""
Properties/Attributes common to all Materials:
* name: str: Name of the material.
* compound_elabid: int: eLabFTW internal id of the compound.
* dimensions: str: Dimensions of the material, in standard format.
The class recognizes the unit of measurement and acts consequently.
* dimensions_unit: str: Unit of measurement - either "mm x mm", "inches" or None.
Specific properties/attributes:
* orientation: str:
* miscut_angle: str:
* miscut_angle_unit: str:
* miscut_direction: str:
* thickness: str:
* thickness_unit: str:
* surface_treatment: str:
* manufacturer: str:
* batch_id: str:
"""
super().__init__(material_data)
try:
self.orientation = self.extra["Orientation"]["value"]
@@ -315,7 +390,28 @@ class Substrate(Material):
class Target(Material):
"""
Target(material_data) - where material_data is a Python dictionary.
Inherits from Material and it's meant to be used exclusively for eLabFTW Resources of the "PLD Target" category.
"""
def __init__(self, material_data):
"""
Properties/Attributes common to all Materials:
* name: str: Name of the material.
* compound_elabid: int: eLabFTW internal id of the compound.
* dimensions: str: Dimensions of the material, in standard format.
The class recognizes the unit of measurement and acts consequently.
* dimensions_unit: str: Unit of measurement - either "mm x mm", "inches" or None.
Specific properties/attributes:
* thickness: str:
* thickness_unit: str:
* shape: str:
* solid_form: str:
* manufacturer: str:
"""
super().__init__(material_data)
try:
self.thickness = self.extra["Thickness"]["value"]
@@ -332,7 +428,21 @@ class Target(Material):
class Proposal:
"""
Proposal(proposal_data) - where proposal_data is a Python dictionary.
Recovers only the relevant info on a proposal linked to the entrypoint sample.
Which currently is just its name.
If the name starts with "Proposal " (space included) that gets omitted from the output.
"""
def __init__(self, proposal_data):
"""
Properties/Attributes:
* name: str: Name of the proposal.
If the name starts with "Proposal " (space included) that gets omitted from the output.
"""
if "Proposal " in proposal_data["title"]:
self.name = proposal_data["title"].replace("Proposal ", "")
else:

View File

@@ -1,8 +1,7 @@
#!/usr/bin/env python3
import os, json, requests, h5py
import numpy as np
# import dotenv
from dotenv import load_dotenv
from getpass import getpass
from APIHandler import APIHandler
from classes import *
@@ -12,9 +11,13 @@ from PIL import Image
def call_entrypoint_from_elabid(elabid):
"""
Calls an entrypoint sample from eLabFTW using its elabid, then returns an object of the Entrypoint class.
Calls a sample from eLabFTW through its elabid, then returns an object of the Entrypoint class.
The Entrypoint serves as the starting point in the construction of the dataset.
If the entry is not a sample (category_title not matching exactly "Sample") returns ValueError.
It's most likely the first error you might encounter (with a valid API key).
Arg: elabid: int eLabFTW internal id of the selected resource.
"""
try:
sample_data = APIHandler(api_key).get_entry_from_elabid(
@@ -34,8 +37,11 @@ def call_material_from_elabid(elabid):
"""
Calls a material from eLabFTW using its elabid, then returns an object of the Material class.
If the entry is neither a PLD Target or a Substrate batch returns ValueError. Such entries always have a category_title key with its value matching exactly "PLD Target" or "Substrate".
If the entry is neither a PLD Target or a Substrate batch returns ValueError.
Such entries always have a category_title key with its value matching exactly "PLD Target" or "Substrate".
Because of an old typo, the value "Subtrate" (second 's' is missing) is also accepted.
arg: elabid: int eLabFTW internal id of the selected resource.
"""
try:
material_data = APIHandler(api_key).get_entry_from_elabid(
@@ -59,9 +65,12 @@ def call_material_from_elabid(elabid):
def call_layers_from_list(elabid_list):
"""
Calls a list of (PLD deposition) experiments from eLabFTW using their elabid - which means the input must be a list of integers instead of a single one - then returns a list of Layer-class objects.
Calls a list of (PLD deposition) experiments from eLabFTW through their elabid's, then returns a list of Layer-class objects.
If one of the entries is not related to a deposition layer (category_title not matching exactly "PLD Deposition") that entry is skipped, with no error raised.
If one of the entries is not related to a deposition layer (category_title not matching exactly "PLD Deposition")
that entry is skipped, with no error raised.
Arg: elabid_list: list(int): list of eLabFTW experiments.
"""
list_of_layers = []
for elabid in elabid_list:
@@ -82,12 +91,20 @@ def call_layers_from_list(elabid_list):
+ str(e)
+ f"\nPlease solve the problem before retrying."
+ "\n\n"
+ f"Last resource attempted to call: {ELABFTW_API_URL}/experiments/{elabid}"
+ f"Last resource attempted to call at base url: /experiments/{elabid}"
)
return list_of_layers # list of Layer-class objects
def call_proposal_from_elabid(elabid):
"""
Calls a proposal item from eLabFTW using their elabid and creates a Proposal-class object.
Returns the proposal's name (method Proposal.name -> str)
If the name starts with "Proposal " (space included) that gets omitted from the output.
Arg: elabid: int eLabFTW internal id of the selected resource.
"""
try:
proposal_data = APIHandler(api_key).get_entry_from_elabid(
elabid, entryType="items"
@@ -110,8 +127,10 @@ def call_proposal_from_elabid(elabid):
def chain_entrypoint_to_batch(sample_object):
"""
Takes an Entrypoint-class object, looks at its .batch_elabid attribute and returns a Material-class object containing data on the substrate batch associated to the starting sample.
Takes an Entrypoint-class object, looks at its .batch_elabid attribute and retrieves data on the substrate batch associated to the starting sample.
Returns a Material-class object.
Arg: sample_object: Entrypoint: Entrypoint-class object.
Dependency: call_material_from_elabid.
"""
material_elabid = sample_object.batch_elabid
@@ -121,10 +140,11 @@ def chain_entrypoint_to_batch(sample_object):
def chain_entrypoint_to_layers(sample_object):
"""
Takes an Entrypoint-class object, looks at its .linked_experiments_elabid attribute (list) and returns a list of Layer-class objects containing data on the deposition layers associated to the starting sample - using the function call_layers_from_list.
The list is sorted by progressive layer number (layer_number attribute).
Takes an Entrypoint-class object, looks at its .linked_experiments_elabid attribute (list) and
retrieves data on the deposition layers associated to the starting sample.
Returns a list of Layer-class objects, sorted by progressive layer number (layer_number attribute).
Arg: sample_object: Entrypoint: Entrypoint-class object.
Dependency: call_layers_from_list.
"""
linked_experiments_elabid = (
@@ -137,8 +157,10 @@ def chain_entrypoint_to_layers(sample_object):
def chain_layer_to_target(layer_object):
"""
Takes a Layer-class object, looks at its .target_elabid attribute and returns a Material-class object containing data on the PLD target used in the deposition of said layer.
Takes a Layer-class object, looks at its .target_elabid attribute and retrieves data on the PLD target used in the deposition of said layer.
Returns a Material-class object.
Arg: layer_object: Layer: Layer-class object.
Dependency: call_material_from_elabid.
"""
target_elabid = layer_object.target_elabid
@@ -148,9 +170,16 @@ def chain_layer_to_target(layer_object):
def deduplicate_instruments_from_layers(layers):
"""
Takes a list of Layer-class objects and for each layer gets the instruments used (laser, depo chamber and RHEED), returns dictionary with one item per category. This means that if more layers share the same instruments it returns a dictionary with just their names as strings (no lists or sub-dictionaries).
For each layer gets the instruments used (laser, depo chamber and RHEED).
Creates three sets with all the instruments used regardless of the layer they've been used for.
Turns the sets into three strings (joined with commas), then returns a dictionary in the format:
{
"laser_system": "Laser A, Laser B...",
"deposition_chamber": "DC A, DC B...",
"rheed_system": RHEED A, RHEED B..."
}
If different layers have different instruments (e.g. laser systems) the user is prompted to only select one.
Arg: layers: list(Layer): List of Layer-class objects.
"""
lasers = []
chambers = []
@@ -175,57 +204,8 @@ def deduplicate_instruments_from_layers(layers):
"deposition_chamber": ", ".join(ded_chambers),
"rheed_system": ", ".join(ded_rheeds),
} # dictionary's name is a joke
# updated_dict = {} # use this for containing the final dataset
# for ded in elegant_dict:
# if len(elegant_dict[ded]) == 0:
# # if len of list is 0 - empty list - raise error
# raise IndexError(f"Missing data: no Laser System, Chamber and/or RHEED System is specified in any of the Deposition-type experiments related to this sample. Fix this on eLabFTW before retrying. Affected list: {ded}.")
# elif len(elegant_dict[ded]) > 1:
# # if len of list is > 1 - too many values - allow the user to pick one
# print("Warning: different instruments have been used for different layers - which is currently not allowed.")
# # there's a better way to do this but I can't remember now for the life of me...
# i = 0
# while i < len(elegant_dict[ded]):
# print(f"{i} - {elegant_dict[ded][i]}")
# i += 1
# ans = None
# while not type(ans) == int or not ans in range(0, len(elegant_dict[ded])):
# ans = input("Please pick one of the previous (0, 1, ...) [default = 0]: ") or "0"
# if ans.isdigit():
# ans = int(ans)
# continue # unnecessary?
# updated_dict[ded] = elegant_dict[ded][ans]
# elif elegant_dict[ded][0] in ["", 0, None]:
# # if len is 1 BUT value is "", 0 or None raise error
# raise ValueError(f"Missing data: a Laser System, Chamber and/or RHEED System which is specified across all the Deposition-type experiments related to this sample is either empty or invalid. Fix this on eLabFTW before retrying. Affected list: {ded}.")
# else:
# # if none of the previous (only 1 value), that single value is used
# updated_dict[ded] = elegant_dict[ded][0]
# instruments_used_dict = {
# "laser_system": updated_dict["Laser Systems"],
# "deposition_chamber": updated_dict["Deposition Chamber"],
# "rheed_system": updated_dict["RHEED Systems"],
# }
return elegant_dict
### OLD CODE
# if 0 in [ len(i) for i in elegant_list ]:
# # i.e. if length of one of the lists in elegant_list is zero (missing data):
# raise IndexError("Missing data: no Laser System, Chamber and/or RHEED System is specified in any of the Deposition-type experiments related to this sample.")
# if not all([ len(i) == 1 for i in elegant_list ]):
# print("Warning: different instruments have been used for different layers - which is currently not allowed.")
# # for every element in elegant list check if len > 1 and if it is
# print("Selecting the first occurence for every category...")
###
# lasers = { f"layer_{lyr.layer_number}": lyr.laser_system for lyr in layers }
# chambers = { f"layer_{lyr.layer_number}": lyr.deposition_chamber for lyr in layers }
# rheeds = { f"layer_{lyr.layer_number}": lyr.rheed_system for lyr in layers }
# instruments_used_dict = {
# "laser_system": lasers,
# "deposition_chamber": chambers,
# "rheed_system": rheeds,
# }
def select_rheed_data(layer):
"""
@@ -309,11 +289,6 @@ def select_rheed_data(layer):
return (rheed_data_file, rheed_image_file)
def download_rheed_data():
return
def analyse_rheed_data(data):
"""
Takes the content of a tsv file and returns a dictionary with timestamps and intensities.
@@ -323,13 +298,15 @@ def analyse_rheed_data(data):
Time Layer1_Int1 Layer1_Int2 Layer1_Int3
-----
Distinct ValueErrors are raised if:
* The array is not 2-dimensional;
* The total number of columns does not equate exactly 1+3 (= 4).
Exceptions:
1. Distinct ValueErrors are raised if:
* The array is not 2-dimensional;
* The total number of columns does not equate at least 1+3 (= 4).
2. If the file has more than 4 columns the function prints a warning, then ignores the other columns.
3. No exception is made for files where the first column is not the time, or the others are not intensities.
Time is expressed in seconds, intensities are adimensional on 8 bits (min. 0, max. 255).
# TO-DO: complete this description...
Written with help from DeepSeek.
"""
# Verifying the format of the input file:
@@ -369,6 +346,10 @@ def make_nexus_schema_dictionary(substrate_object, layers):
and a list of Layer-class objects (output of the chain_entrypoint_to_layers() function).
Returns dictionary with the same schema as the NeXus standard for PLD fabrications.
Args:
substrate_object: Substrate: Substrate-class object.
layers: list(Layer): List of Layer-class objects.
"""
instruments = deduplicate_instruments_from_layers(layers)
pld_fabrication = {
@@ -506,7 +487,18 @@ def make_nexus_schema_dictionary(substrate_object, layers):
return pld_fabrication
def build_nexus_file(pld_fabrication, output_path):
def build_nexus_file(pld_fabrication, output_path="output/nffa-di_unnamed.h5"):
"""
The function which actually builds the NeXus file for *PLD DEPOSITIONS*.
Saves the file in the specified directory.
Args:
pld_fabrication: A dictionary with a specific schema, one only the function
make_nexus_schema_dictionary should make.
output_path: The full path to the output file, including filename complete with extension.
It's a string, which should be produced with os.path.
Default value is: "output/nffa-di_unnamed.h5" - which is NOT NFFA-DI compliant.
"""
# NOTE: look at the mail attachment from Emiliano...
with h5py.File(output_path, "w") as f:
nx_pld_entry = f.create_group("pld_fabrication")
@@ -846,6 +838,7 @@ def build_nexus_file(pld_fabrication, output_path):
if image_path and os.path.isfile(image_path):
img = Image.open(image_path).convert("L")
heatmap_matrix = np.array(img, dtype=np.uint8) # or None
# heatmap_matrix = heatmap_matrix.astype(np.float32) / 255.0 # toggle to normalize matrix values
if heatmap_matrix is not None:
heatmap = nx_rheed_layer.create_dataset(
@@ -875,32 +868,20 @@ def build_nexus_file(pld_fabrication, output_path):
# * Layer.fetch_textual_uploads() - dictionary
# * Layer.fetch_images() - dictionary
# nx_rheed = nx_pld_entry.create_group("rheed_data")
# nx_rheed.attrs["NX_class"] = "NXdata"
# nx_rheed.create_dataset("time", data=rheed_osc["time"])
# nx_rheed["time"].attrs["units"] = "s"
# nx_rheed.create_dataset("intensity", data=rheed_osc["intensity"])
# #nx_rheed["intensity"].attrs["units"] = "counts"
# nx_rheed["intensity"].attrs["long_name"] = "RHEED intensity"
# nx_rheed.attrs["signal"] = "intensity"
# nx_rheed.attrs["axes"] = "layer:time:channel"
# nx_rheed.attrs["layer_indices"] = [0] # asse layer
# nx_rheed.attrs["time_indices"] = [1] # asse tempo
# nx_rheed.attrs["channel_indices"] = [2]
if __name__ == "__main__":
# TO-DO: place the API base URL somewhere else.
ELABFTW_API_URL = "https://elabftw.fisica.unina.it/api/v2"
api_key = getpass("Paste API key here: ")
elabid = input("Enter elabid of your starting sample [default = 1111]: ") or 1111
load_dotenv()
api_key = os.getenv("api_key") or getpass("Paste API key here: ")
elabid = (
os.getenv("elabid")
or input("Enter elabid of your starting sample [default = 1111]: ")
or 1111
)
handler = APIHandler(api_key)
data = handler.get_entry_from_elabid(elabid)
sample = Entrypoint(data)
sample_name = sample.name.strip().replace(" ", "_")
operative_unit = "Napoli"
operative_unit = os.getenv("operative_unit") or None
if sample.proposal:
sample_proposal = call_proposal_from_elabid(sample.proposal)
else:
@@ -908,26 +889,17 @@ if __name__ == "__main__":
substrate_object = chain_entrypoint_to_batch(sample) # Substrate-class object
layers = chain_entrypoint_to_layers(sample) # list of Layer-class objects
n_layers = len(layers) # total number of layers on the sample
result = make_nexus_schema_dictionary(substrate_object, layers)
# print(make_nexus_schema_dictionary(substrate_object, layers)) # debug
fn_base = (
"nffa-di_"
+ (f"{sample_proposal}_" if sample_proposal else "")
+ operative_unit
+ (f"{operative_unit}_" if operative_unit else "")
+ "_"
+ sample_name
)
result = make_nexus_schema_dictionary(substrate_object, layers)
with open(f"output/{fn_base}.json", "w") as f:
json.dump(result, f, indent=3)
# TO-DO: remove the hard-coded path of the RWA file
# ideally the script should download a TXT/CSV file from each layer
# (IF PRESENT ←→ also handle missing file error)
# and merge all data in a single file to analyse it
# WARNING: fails if file is missing
# This one tries to open a png image.
# Emiliano said to keep it to one image per layer tops.
# In this test I will only consider one image.
# TO-DO: make it format-agnostic. If not possible, make it PNG-only.
# mx = mx.astype(np.float32) / 255.0 # consider deleting???
build_nexus_file(result, output_path=f"output/{fn_base}.h5")