diff --git a/src/caosadvancedtools/serverside/example_script.py b/src/caosadvancedtools/serverside/example_script.py index 3f8e6d1d9152c42427720c57462bb362923ff2d3..d1ef787bb0b0d47849cf0433f8481d110a95afd6 100644 --- a/src/caosadvancedtools/serverside/example_script.py +++ b/src/caosadvancedtools/serverside/example_script.py @@ -29,12 +29,77 @@ with the generic_analysis module. """ import argparse +import logging import sys from argparse import RawTextHelpFormatter +import caosdb as db +import matplotlib.pyplot as plt +import numpy as np +from caosadvancedtools.cfood import assure_property_is + +logger = logging.getLogger(__name__) + def main(args): - print(args.entityid) + # TODO can these checks be replaced by a more declaritive appoach? + try: + dataAnalysisRecord = db.Record(id=args.entityid).retrieve() + except db.TransactionError: + logger.error("Cannot retrieve dataAnalysisRecord with id ={}".format( + args.entityid + )) + + # The script may require certain information to exist. Here, we expect that + # a InputDataSet Property exists that references a numpy file. + + if (dataAnalysisRecord.get_property("InputDataSet") is None + or db.apiutils.is_reference( + dataAnalysisRecord.get_property("InputDataSet"))): + + raise RuntimeError("InputDataSet Refenrence must exist.") + + # ####### this core might be replaced by a call to another script ####### # + # Download the data + npobj = db.File( + id=dataAnalysisRecord.get_property("InputDataSet")).retrieve() + npfile = npobj.download() + data = np.load(npfile) + + # Plot data + filename = "hist.png" + plt.hist(data) + plt.savefig() + + mean = data.mean() + # ####################################################################### # + + # Insert the result plot + # TODO: how do we find a good file path?? + fig = db.File(file=filename, path="/uploaded/something/"+filename) + fig.insert() + + # Add the result to the analysis Record + # An update should only be done if necessary: assure_property_is should be + # used instead of direct calls to 'update'. + + assure_property_is( + dataAnalysisRecord, + "mean_value", + mean, + ) + # TODO this is not really meaningful since an uploaded file will always + # be different.... Compare checksums of files? + assure_property_is( + dataAnalysisRecord, + "result", + fig.id, + ) + # TODO what should be done with the old file? Removed if not referenced? + + # TODO inform about updates (reuse stuff from crawler.py?) + # TODO sketch meaningful logging + # TODO how to send an email? def parse_args():