-
Notifications
You must be signed in to change notification settings - Fork 2
Estimate transmission wrapper #365
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
pjnaughton
wants to merge
8
commits into
main
Choose a base branch
from
estimate_transmission_wrapper
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+138
−101
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
57c610e
estimate_transmission wrapper
pjnaughton 8f33f29
Removing xia2.overload wrapper
pjnaughton bc6af9e
Moving to use subprocess.run
pjnaughton c9c153f
Using max pixel to scale the transmission, making strategy service us…
pjnaughton 0f0be5c
Changing chainmap logic to collect all parameters from recipe
pjnaughton 2a83cde
fixing typo
pjnaughton 7aa9261
Saving the histogram to a json file
pjnaughton ae25331
Using percentile pixel
pjnaughton File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,120 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| import shutil | ||
| import subprocess | ||
| from collections import Counter | ||
| from pathlib import Path | ||
| from itertools import accumulate | ||
| from dials.array_family import flex | ||
|
|
||
| from dlstbx.wrapper import Wrapper | ||
|
|
||
| class EstimateTransmissionWrapper(Wrapper): | ||
| _logger_name = "dlstbx.wrap.estimate_transmission" | ||
|
|
||
| def run(self): | ||
| assert hasattr(self, "recwrap"), "No recipewrapper object found" | ||
|
|
||
| params = self.recwrap.recipe_step["job_parameters"] | ||
| working_directory = Path(params["working_directory"]) | ||
| results_directory = Path(params["results_directory"]) | ||
|
|
||
| beamline = params["beamline"] | ||
| pixel_percentile = params["pixel_percentile"].get(beamline, 100) / 100 | ||
| target_countrate_pct = params["target_countrate_pct"].get(beamline, 50) / 100 | ||
| transmission = float(params["transmission"]) | ||
| file = params["input_file"] | ||
|
|
||
| commands = [ | ||
| ("dials.import", ["dials.import", file]), | ||
| ("dials.find_spots", [ "dials.find_spots", | ||
| "imported.expt", | ||
| "ice_rings.filter=True"], | ||
| ), | ||
| ] | ||
|
|
||
| for command, script in commands: | ||
| result = subprocess.run(script, cwd=working_directory, check=True) | ||
|
|
||
| if result.returncode: | ||
| self.log.info(f"{command} failed with return code {result.returncode}") | ||
| self.log.info(result.stderr) | ||
|
|
||
| self.log.debug(f"Command output:\n{result.stdout}") | ||
| self.log.debug(f"From command: {script}") | ||
| return False | ||
|
|
||
| experiment_file = working_directory / "imported.expt" | ||
| with experiment_file.open("r") as f: | ||
| experiment = json.load(f) | ||
| trusted_range = experiment["detector"][0]["panels"][0]["trusted_range"][1] | ||
|
|
||
| reflection_file = working_directory / "strong.refl" | ||
| reflections = flex.reflection_table.from_file(reflection_file) | ||
| counts_hist = self.build_hist_from_reflections(reflections) | ||
|
|
||
| num_counts = list(counts_hist.keys()) | ||
| num_pixels = list(counts_hist.values()) | ||
|
|
||
| index_of_pixel_percentile = self.get_percentile_index(num_pixels, pixel_percentile) | ||
| counts_at_percentile = int(num_counts[index_of_pixel_percentile]) | ||
|
|
||
| pixel_countrate_pct = counts_at_percentile / trusted_range | ||
| self.log.info(f"The countrate percentage of the {pixel_percentile}% most intense pixel is {pixel_countrate_pct}") | ||
| scale_factor = target_countrate_pct / pixel_countrate_pct | ||
|
|
||
| scaled_transmission = min(1, (transmission * scale_factor) / 100) | ||
| self.log.info(f"Scaled transmission is : {scaled_transmission}") | ||
|
|
||
| self.recwrap.send_to( | ||
| "strategy", | ||
| {"parameters": {"scaled_transmission": float(scaled_transmission)}}, | ||
| ) | ||
|
|
||
| results_directory.mkdir(parents=True, exist_ok=True) | ||
| output_files = ["dials.find_spots.log"] | ||
| for output_file in output_files: | ||
| source_file = working_directory / output_file | ||
| destination = results_directory / output_file | ||
|
|
||
| if not source_file.exists(): | ||
| self.log.info(f"{source_file=} does not exsist") | ||
| return False | ||
|
|
||
| self.log.info(f"Copying {str(source_file)} to {str(destination)}") | ||
| shutil.copy(source_file, destination) | ||
|
|
||
| self.save_hist_to_json(counts_hist, trusted_range, results_directory) | ||
|
|
||
| self.log.info("Done.") | ||
| return True | ||
|
|
||
| def build_hist_from_reflections(self, reflections): | ||
| "Iterate through the shoeboxes to a reflection and generate a pixel histogram" | ||
|
|
||
| shoeboxes = reflections["shoebox"] | ||
| counter = Counter() | ||
| for sbox in shoeboxes: | ||
| counter.update(sbox.data.as_numpy_array().ravel()) | ||
|
|
||
| sorted_counter = sorted(counter.items()) | ||
| return {str(int(k)): v for k, v in sorted_counter} | ||
|
|
||
| def get_percentile_index(self, num_pixels, percentile): | ||
| threshold = sum(num_pixels) * percentile | ||
|
|
||
| for i, cum_sum in enumerate(accumulate(num_pixels)): | ||
| if cum_sum >= threshold: | ||
| return i | ||
|
|
||
| return len(num_pixels) | ||
|
|
||
| def save_hist_to_json(self, hist, max_trusted_value, results_dir): | ||
| results_path = results_dir / "overload.json" | ||
| self.log.info(f"Saving counts histogram to {str(results_path)}") | ||
| with open(results_path, 'w') as f: | ||
| json.dump({ "counts": hist, | ||
| "overload_limit": max_trusted_value}, f, indent=2) | ||
|
|
||
| self.log.info("Saved.") |
This file was deleted.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Discussed on slack that rather than using the recommended_max transmission to set the transmission limits, the recommended transmission should be used in place of recipe_step.transmission (i.e. instead of the transmission value from the Agamemnon recipe). This means that the recommended transmission will be scaled appropriately for wavelength and resolution.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I have tested with Phasing which has a recommended transmission of .25, and the recommended transmission from our wrapper is .44 and after scaling it returns to use .36 transmission in the dc. You can see it at https://ispyb-test.diamond.ac.uk/dc/visit/mx23694-156/id/21149301 for Phasing wedge 1