-
Notifications
You must be signed in to change notification settings - Fork 77
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
Interpolation of RF predictions with cosZD, for homogeneous performance #1320
base: main
Are you sure you want to change the base?
Conversation
to avoid jumps when using RFs trained on a discrete set of pointings
Codecov ReportAttention: Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #1320 +/- ##
==========================================
- Coverage 73.52% 73.27% -0.25%
==========================================
Files 134 134
Lines 14215 14321 +106
==========================================
+ Hits 10451 10494 +43
- Misses 3764 3827 +63 ☔ View full report in Codecov by Sentry. |
command-line options The interpolation can be switched on for the three reconstructions independently (energy, gammaness, direction) By default the correction is applied. If no MC DL1 training directory is provided, the path will be built from the path of the RF models. If directory does not exist the option is simply deactivated
Hi @moralejo |
Will do. What is better, just the zenith and azimuth values, or a list of the directory names? |
I think the table of values that you can use directly at inference would be great (with appropriate metadata such as the date of export). |
Can you clarify exactly what metadata (and how? Just lines starting with # or whatever?) |
What if we just write in the config the two arrays of zeniths and azimuths? I did not implement it yet, it would be like this: "random_forest_zd_interpolation": {
} |
Instead of closest angular distance we now take the closest nodes in alt_tel on the same side of the culmination (same sign of sin_az_tel)
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.
Copilot reviewed 2 out of 3 changed files in this pull request and generated no suggestions.
Files not reviewed (1)
- lstchain/data/lstchain_standard_config.json: Language not supported
Comments skipped due to low confidence (1)
lstchain/reco/dl1_to_dl2.py:215
- The word 'dictionnary' is misspelled. It should be 'dictionary'.
config: dictionnary containing configuration
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.
Copilot reviewed 2 out of 3 changed files in this pull request and generated no comments.
Files not reviewed (1)
- lstchain/data/lstchain_standard_config.json: Language not supported
Comments suppressed due to low confidence (1)
lstchain/scripts/lstchain_dl1_to_dl2.py:164
- Ensure that the
training_pointings
array is correctly populated and used. If the directory does not exist, the interpolation should be switched off.
if dl1_training_dir.is_dir():
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.
Hi Abelardo,
Sorry for the delay (and I still need to finish this later...).
I have made a couple of comments for improvement in the code/readability but overall the core logic looks good to me.
DL2 pandas dataframe with additional columns alt0, alt1, w0, w1 | ||
|
||
""" | ||
pd.options.mode.copy_on_write = True |
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.
This will change the behaviour globally.
I'd suggest either to move it at the module level if that is wanted. Otherwise use context management to set it locally:
with pd.option_context('mode.copy_on_write', True):
...
@@ -51,6 +53,159 @@ | |||
'update_disp_with_effective_focal_length' | |||
] | |||
|
|||
def add_zd_interpolation_info(dl2table, training_zd_deg, training_az_deg): |
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.
wouldn't using astropy units for quantities be better here?
alt_tel = dl2table['alt_tel'] | ||
az_tel = dl2table['az_tel'] | ||
|
||
training_alt_rad = np.pi / 2 - np.deg2rad(training_zd_deg) |
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.
continuing comment about astropy quantities: it would avoid manual conversion
training_az_rad = np.deg2rad(training_az_deg) | ||
|
||
tiled_az = np.tile(az_tel, | ||
len(training_az_rad)).reshape(len(training_az_rad), |
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.
tiled_az = np.broadcast_to(az_tel[:, np.newaxis], (len(dl2table), len(training_az_rad)))
would be more memory efficient as it would not create a copy of the array
0.5, (cos_tel_zd - c0) / (c1 - c0)) | ||
w0 = 1 - w1 | ||
|
||
# Update the dataframe: |
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 don't see why converting to Series is necessary?
|
||
# Update the dataframe: | ||
dl2table = dl2table.assign(alt0=pd.Series(closest_alt).values, | ||
alt1=pd.Series(second_closest_alt).values, |
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.
please use more explicit names for alt0, alt1, c0 and c1 in the dl2table that will end up being written
is_classifier = isinstance(rf, RandomForestClassifier) | ||
|
||
# keep original alt_tel values: | ||
param_array.rename(columns={"alt_tel": "original_alt_tel"}, inplace=True) |
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 think it would be easier to change the features rather than this game of name-swapping:
features_copy = features.copy() # avoid modifying features outside the function
alt_index_in_features = features_copy.index('alt_tel')
features_copy[alt_index_in_features] = 'alt0'
predict_0 = rf.predict(param_array[features_copy])
features_copy[alt_index_in_features] = 'alt1'
predict_1 = ...
that's it
c1 = dir.find('_theta_') + 7 | ||
c2 = dir.find('_az_', c1) + 4 | ||
c3 = dir.find('_', c2) |
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.
# Regular expression to extract theta and az values
pattern = r"theta_(\d+\.\d+)_az_(\d+\.\d+)_"
# Search for matches
match = re.search(pattern, name)
if match:
theta = float(match.group(1)) # First captured group is theta
az = float(match.group(2)) # Second captured group is az
print(f"Theta: {theta}, Az: {az}")
else:
print("Pattern not found!")
would be more robust to find digital numbers
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.
This function could even go to lstchain.paths module
# by the discrete set of pointings in the RF training sample. | ||
if 'random_forest_zd_interpolation' in config.keys(): | ||
zdinter = config['random_forest_zd_interpolation'] | ||
if 'interpolate_energy' in zdinter.keys(): |
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.
slightly more readable:
interpolate_energy = zdinter.get('interpolate_energy', False)
and then you don't need to set it first, it is set to False here if interpolate_energy
not in zdinter
Hi I think we should go beyond testing actually. Ideally, the training pointing directions should be saved with the models, and this PR should prepare for that imho.
To save the pointing directions as ascii files, I'd recommend starting from astropy tables and save to |
"interpolate_energy": true, | ||
"interpolate_gammaness": true, | ||
"interpolate_direction": true, | ||
"DL1_training_dir": null |
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.
see my comment in the main discussion about saving training directions with the models
if 'random_forest_zd_interpolation' in config.keys(): | ||
zdinter = config['random_forest_zd_interpolation'] | ||
if 'dl1_training_dir' in zdinter.keys(): | ||
dl1_training_dir = zdinter['dl1_training_dir'] |
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.
dl1_training_dir = zdinter.get('dl1_trainin_dir', None)
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.
Left some minor comments.
c1 = dir.find('_theta_') + 7 | ||
c2 = dir.find('_az_', c1) + 4 | ||
c3 = dir.find('_', c2) |
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.
This function could even go to lstchain.paths module
logger.warning('RF training pointings (az_deg, zd_deg):') | ||
logger.warning(training_pointings) |
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.
log.info()
here, it is the expected behavior
# Build name of DL1 MC training files assuming standard pattern: | ||
dummy = models_path.as_posix().replace('/data/models', '/data/mc/DL1') | ||
dl1_training_dir = (Path(dummy[:dummy.rfind('/dec')] + | ||
'/TrainingDataset/GammaDiffuse/' + | ||
dummy[dummy.rfind('/dec') + 1:])) |
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 think this should go to lstchain.paths
module.
if interpolate_direction: | ||
logger.warning(' direction reconstruction Random Forest') | ||
|
||
if 'random_forest_zd_interpolation' in config.keys(): |
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.
if 'random_forest_zd_interpolation' in config.keys(): | |
if 'random_forest_zd_interpolation' in config: |
dl1_training_dir = None | ||
training_pointings = None | ||
if True in interpolate_rf.values(): | ||
logger.warning('Cos(zenith) interpolation will be used in:') |
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.
log.info
Regarding metadata, if you're using astropy Tables to later write ECSV files, you can define the metadata as: pointing_table = Table(...)
pointing_table.meta["export_date"] = datetime.today().strftime('%Y-%m-%d')
pointing_table.write("filepath_pointings.ecsv", format="ascii.ecsv") |
This should solve the issue of RF "performance jumps" at high zenith angles, when the pointing goes through the middle points between training nodes. See #1317
NOTE: this is a different implementation of the interpolation approach proposed by @gabemery, see branch https://github.com/cta-observatory/cta-lstchain/tree/dl2_RF_interpolate)
If the interpolation option is activated we call the RF predictors twice, for each of the two closest MC training nodes, then interpolate (or extrapolate) the values to the actual telescope pointing for each event.
Currently the training sample pointings are obtained from the path to the training sample(provided via config file). A better solution would be to add to the .sav files an array with the zenith and azimuth values of the MC training nodes.