diff --git a/lib/inat_inferrer.py b/lib/inat_inferrer.py index 2bea37c..5b74aad 100644 --- a/lib/inat_inferrer.py +++ b/lib/inat_inferrer.py @@ -19,6 +19,8 @@ from lib.coord_encoder import CoordEncoder from lib.vision_inferrer import VisionInferrer from lib.model_taxonomy_dataframe import ModelTaxonomyDataframe +from lib.model_taxonomy_dataframe import propagate_max_down_tree_inplace +from lib.model_taxonomy_dataframe import aggregate_taxonomy_up_inplace pd.options.mode.copy_on_write = True @@ -43,6 +45,9 @@ def __init__(self, config): self.setup_coord_encoder() self.setup_geo_model() self.upload_folder = "static/" + self.new_scoring = self.config["new_scoring"] if "new_scoring" in self.config else False + self.innernode_geomodel = self.config["geomodel_innernode"] if "geomodel_innernode" in self.config else False + self.innernode_scoring = self.config["innernode_scoring"] if "innernode_scoring" in self.config else False def setup_taxonomy(self): self.taxonomy = ModelTaxonomyDataframe( @@ -97,6 +102,8 @@ def setup_synonyms(self): # record when the synonyms file was updated to know later when to refresh it self.synonyms_path_updated_at = os.path.getmtime(self.config["synonyms_path"]) + # TODO: restore synonym taxonomy when it works with innernodes + # and `aggregate_taxonomy_up_inplace` self.setup_synonym_taxonomy() def setup_synonym_taxonomy(self): @@ -241,7 +248,9 @@ def geo_model_predict(self, lat, lng, encoder="h3", debug=False): if debug: print("Geo Time: %0.2fms" % ((time.time() - start_time) * 1000.)) - return geo_scores + if geo_scores is None: + return None + return np.array(geo_scores, dtype=np.float32) def taxon_exists(self, taxon_id): return taxon_id in self.taxonomy.df.index @@ -256,7 +265,25 @@ def lookup_taxon(self, taxon_id): print(f"taxon `{taxon_id}` does not exist in the taxonomy") raise e + def taxonomy_length_zeros(self): + return np.zeros(len(self.taxonomy.df), dtype=np.float32) + + def taxonomy_length_nan(self): + return np.full(len(self.taxonomy.df), np.nan, dtype=np.float32) + + def pad_to_match_length(self, arr, comparison): + length_diff = len(comparison) - len(arr) + if length_diff == 0: + return arr + if length_diff < 0: + raise ValueError("Cannot pad an array when the comparison array is shorter") + return np.pad(arr, (0, length_diff)) + def predictions_for_image(self, file_path, lat, lng, filter_taxon, debug=False): + if self.new_scoring: + # print("USING NEW SCORING FOR predictions_for_image") + return self.predictions_for_image_new_scoring(file_path, lat, lng, filter_taxon, debug) + if debug: start_time = time.time() image = InatInferrer.prepare_image_for_inference(file_path) @@ -267,17 +294,291 @@ def predictions_for_image(self, file_path, lat, lng, filter_taxon, debug=False): combined_scores = self.combine_results( raw_vision_scores, raw_h3_geo_scores, filter_taxon, raw_raster_geo_scores, debug ) - combined_scores = self.map_result_synonyms(combined_scores, debug) + # TODO: restore synonym taxonomy when it works with innernodes + # combined_scores = self.map_result_synonyms(combined_scores, debug) # for any taxon that doesn't have a geo threshold, set it to 1 which is the highest # possible value, and thus all its taxa will not be considered "expected nearby" combined_scores["geo_threshold"] = combined_scores["geo_threshold"].fillna(1) if debug: print("Prediction Time: %0.2fms" % ((time.time() - start_time) * 1000.)) + return { "combined_scores": combined_scores, "features": vision_model_results["features"] } + def filter_raw_vision_and_geo_scores(self, filter_taxon, raw_vision_scores, + raw_h3_geo_scores, thresholds): + no_geo_scores = (raw_h3_geo_scores is None) + if filter_taxon is not None: + # using nested set left and right values, select the filter taxon and its descendants + filtered_taxa = self.taxonomy.spatial_df.query( + f'(left >= {filter_taxon["left"]} and right <= {filter_taxon["right"]}) or ' + f'(left < {filter_taxon["left"]} and right > {filter_taxon["right"]})' + ) + + filtered_positions = filtered_taxa["spatial_class_id"].to_numpy(dtype=np.int32) + mask = np.ones(len(self.taxonomy.df), dtype=bool) + mask[filtered_positions] = False + raw_vision_scores[mask] = np.nan + thresholds[mask] = np.nan + if not no_geo_scores: + raw_h3_geo_scores[mask] = np.nan + normalized_vision_scores = raw_vision_scores / np.nansum(raw_vision_scores) + else: + normalized_vision_scores = raw_vision_scores + return [raw_vision_scores, raw_h3_geo_scores, normalized_vision_scores, thresholds] + + def predictions_for_image_new_scoring(self, file_path, lat, lng, filter_taxon, debug=False): + if self.innernode_scoring: + # print("USING INNERNODE SCORING FOR predictions_for_image") + return self.predictions_for_image_innernnode(file_path, lat, lng, filter_taxon, debug) + + if debug: + start_time = time.time() + image = InatInferrer.prepare_image_for_inference(file_path) + + if debug: + print("image prep time: %0.2fms" % ((time.time() - start_time) * 1000.)) + start_time = time.time() + + vision_model_results = self.vision_predict(image, debug) + raw_vision_scores = vision_model_results["predictions"] + raw_h3_geo_scores = self.geo_model_predict(lat, lng, encoder="h3", debug=debug) + no_geo_scores = (raw_h3_geo_scores is None) + + if debug: + print("Prediction Time: %0.2fms" % ((time.time() - start_time) * 1000.)) + start_time = time.time() + + raw_vision_scores = self.pad_to_match_length(raw_vision_scores, self.taxonomy.df) + if not no_geo_scores: + raw_h3_geo_scores = self.pad_to_match_length(raw_h3_geo_scores, self.taxonomy.df) + + raw_vision_scores, raw_h3_geo_scores, normalized_vision_scores, thresholds = self. \ + filter_raw_vision_and_geo_scores( + filter_taxon, raw_vision_scores, raw_h3_geo_scores, + self.taxonomy.spatial_df["geo_threshold"].to_numpy(dtype=np.float32) + ) + + if no_geo_scores: + combined_scores = normalized_vision_scores + normalized_geo_scores = None + else: + normalized_geo_scores = np.maximum(raw_h3_geo_scores, 0.005) + combined_scores = ( + normalized_vision_scores * normalized_geo_scores + ) + + spatial_scores = self.taxonomy.spatial_df.copy(deep=False) + spatial_scores["vision_score"] = raw_vision_scores + spatial_scores["normalized_vision_score"] = normalized_vision_scores + if no_geo_scores: + spatial_scores["geo_score"] = 0 + spatial_scores["normalized_geo_score"] = 0 + else: + spatial_scores["geo_score"] = raw_h3_geo_scores + spatial_scores["normalized_geo_score"] = normalized_geo_scores + spatial_scores["combined_score"] = combined_scores + + if no_geo_scores: + spatial_scores["normalized_combined_score"] = spatial_scores["combined_score"] + else: + sum_of_combined_scores = np.nansum(combined_scores) + if sum_of_combined_scores > 0: + normalized_combined_scores = combined_scores / sum_of_combined_scores + spatial_scores["normalized_combined_score"] = normalized_combined_scores + else: + spatial_scores["normalized_combined_score"] = 0 + + return { + "combined_scores": spatial_scores, + "features": vision_model_results["features"] + } + + def predictions_for_image_innernnode(self, file_path, lat, lng, filter_taxon, debug=False): + if debug: + start_time = time.time() + image = InatInferrer.prepare_image_for_inference(file_path) + + if debug: + print("image prep time: %0.2fms" % ((time.time() - start_time) * 1000.)) + start_time = time.time() + + vision_model_results = self.vision_predict(image, debug) + raw_vision_scores = vision_model_results["predictions"] + vision_length = len(raw_vision_scores) + raw_h3_geo_scores = self.geo_model_predict(lat, lng, encoder="h3", debug=debug) + no_geo_scores = (raw_h3_geo_scores is None) + + if debug: + print("Prediction Time: %0.2fms" % ((time.time() - start_time) * 1000.)) + start_time = time.time() + + raw_vision_scores = self.pad_to_match_length(raw_vision_scores, self.taxonomy.df) + if not no_geo_scores: + raw_h3_geo_scores = self.pad_to_match_length(raw_h3_geo_scores, self.taxonomy.df) + + raw_vision_scores, raw_h3_geo_scores, normalized_vision_scores, thresholds = self. \ + filter_raw_vision_and_geo_scores( + filter_taxon, raw_vision_scores, raw_h3_geo_scores, + self.taxonomy.spatial_df["geo_threshold"].to_numpy(dtype=np.float32) + ) + + if no_geo_scores: + normalized_vision_scores[np.isnan(normalized_vision_scores)] = 0 + combined_scores = normalized_vision_scores.copy() + normalized_geo_scores = None + aggregate_taxonomy_up_inplace( + self.taxonomy.aggregation_index.parent_position, + self.taxonomy.aggregation_index.postorder, + min_arrays=(thresholds,), + max_arrays=(), + sum_arrays=( + normalized_vision_scores, + combined_scores + ) + ) + else: + raw_h3_geo_scores_leaves = raw_h3_geo_scores[:vision_length] + raw_h3_geo_scores_leaves = self.pad_to_match_length( + raw_h3_geo_scores_leaves, + self.taxonomy.df + ) + original_raw_h3_geo_scores_leaves = raw_h3_geo_scores_leaves.copy() + normalized_geo_scores = np.maximum(raw_h3_geo_scores, 0.005) + unaggregated_normalized_vision_score = normalized_vision_scores.copy() + # this makes non leaf combined scores 0 or nan if there is no vision score + combined_scores = ( + normalized_vision_scores * normalized_geo_scores + ) + combined_scores[np.isnan(combined_scores)] = 0 + normalized_vision_scores[np.isnan(normalized_vision_scores)] = 0 + raw_h3_geo_scores[np.isnan(raw_h3_geo_scores)] = 0 + aggregate_taxonomy_up_inplace( + self.taxonomy.aggregation_index.parent_position, + self.taxonomy.aggregation_index.postorder, + min_arrays=(thresholds,), + max_arrays=( + raw_h3_geo_scores, + raw_h3_geo_scores_leaves + ), + sum_arrays=(combined_scores,) + ) + + spatial_scores = self.taxonomy.spatial_df.copy(deep=False) + spatial_scores["vision_score"] = raw_vision_scores + spatial_scores["normalized_vision_score"] = normalized_vision_scores + if no_geo_scores: + spatial_scores["geo_score"] = 0 + spatial_scores["normalized_geo_score"] = 0 + else: + spatial_scores["geo_score"] = raw_h3_geo_scores + spatial_scores["normalized_geo_score"] = normalized_geo_scores + spatial_scores["leaf_geo_score"] = raw_h3_geo_scores_leaves + spatial_scores["combined_score"] = combined_scores + spatial_scores["original_combined_score"] = combined_scores + spatial_scores["geo_threshold"] = thresholds + + if no_geo_scores: + spatial_scores["normalized_combined_score"] = spatial_scores["combined_score"] + spatial_scores["dggd_combined"] = spatial_scores["combined_score"] + else: + sum_of_combined_scores = spatial_scores.query( + "leaf_class_id.notnull()" + )["combined_score"].sum() + if sum_of_combined_scores > 0: + normalized_combined_scores = combined_scores / sum_of_combined_scores + spatial_scores["normalized_combined_score"] = normalized_combined_scores + else: + spatial_scores["normalized_combined_score"] = 0 + + # at genera, calculate the difference in the direct genus geo score and the aggregated + # geo scored from descendants + direct_genus_geo_diff = ( + spatial_scores["geo_score"] - spatial_scores["leaf_geo_score"] + ).where(spatial_scores["rank_level"].eq(20), 0.0).to_numpy(dtype=np.float32, copy=True) + + # send that genus geo diff down to leaves + propagate_max_down_tree_inplace( + direct_genus_geo_diff, + self.taxonomy.aggregation_index.parent_position, + self.taxonomy.aggregation_index.preorder + ) + + # TODO: the rest of the scoring here is still a work in progress. I'm still evaluating + # different methods to how we weight and apply the genus geo difference to leaf nodes. + + # Ultimately this will produce an alternate combined_score for leaves. That combined + # score will be greater than the original leaf combined score. The difference is the + # weight of the "surrogate", or the amount of extra score we will apply to the genus + # that is not visible in the leaves alone + + dggd_factor = direct_genus_geo_diff * 0.5 + # dggd_factor = direct_genus_geo_diff * spatial_scores["normalized_combined_score"] + dggd_geo_score = original_raw_h3_geo_scores_leaves + dggd_factor + dggd_normalized_geo_score = np.maximum(dggd_geo_score, 0.005) + # dggd_combined represents the original leaf combined scores plus the weight of the + # surrogate data that will be applied to genera + spatial_scores["dggd_combined"] = dggd_normalized_geo_score * \ + unaggregated_normalized_vision_score + + # TODO: this bit of scoring is also still in evaluation. Without this, the leaf combined + # scores do not change and after applying the innernode extra genus weighting, the order + # and relative differences between leaf scores remain exactly the same. In essence - + # without this out top1 always remains the top1, it just has a lower score + + # What changes is the scale of the scores - i.e. all leaf combined scores will be lower + # than they originally were because genera have more weight. What I'm testing here is + # should we sometimes spread some of that extra genus weight to leaves to minimize how + # much leaf combined scores get lowered by this approach + + # If we don't want to alter the relative difference of leaf combined scores, remove + # combined_score from the manipulations in the new few lines, and from the aggregation + # below + + # weight = 0.5 + # spatial_scores["combined_score"] = weight * spatial_scores["combined_score"] + \ + # (1 - weight) * spatial_scores["dggd_combined"] + + dggd_combined = spatial_scores["dggd_combined"].to_numpy(dtype=np.float32, copy=True) + # combined_scores = spatial_scores["combined_score"].to_numpy(dtype=np.float32, copy=True) + dggd_combined[np.isnan(dggd_combined)] = 0 + aggregate_taxonomy_up_inplace( + self.taxonomy.aggregation_index.parent_position, + self.taxonomy.aggregation_index.postorder, + min_arrays=(), + max_arrays=(), + sum_arrays=(dggd_combined,) + ) + spatial_scores["dggd_combined_aggregated"] = dggd_combined + # spatial_scores["combined_score"] = combined_scores + + sum_of_genus_diff_combined = spatial_scores.query( + "leaf_class_id.notnull()" + )["dggd_combined"].sum() + spatial_scores["dggd_combined_normalized"] = spatial_scores[ + "dggd_combined_aggregated" + ] / sum_of_genus_diff_combined + # re-normalize the combined scores this time against the sum of the dggd_combined + # scores. This is the step where the original leaf combined scores get lowered - + # relative to how much genera are getting boosted. If we did not alter the combined + # scores just above, then the relative difference in leaf combined scores remain + # exactly the same (i.e. positions do not change), just the values are lower + normalized_combined_score_post_geo = combined_scores / sum_of_genus_diff_combined + # taxa below genus retain their original combined scores, re-normalized. Genera and + # above use the dggd_combined scores with enhanced weight + spatial_scores["normalized_combined_score"] = np.where( + spatial_scores["rank_level"] < 20, + normalized_combined_score_post_geo, + spatial_scores["dggd_combined_normalized"], + ) + + return { + "combined_scores": spatial_scores, + "features": vision_model_results["features"] + } + def combine_results( self, raw_vision_scores, raw_geo_scores, filter_taxon, raw_raster_geo_scores=None, debug=False @@ -293,11 +594,10 @@ def combine_results( # add a column for vision scores leaf_scores["vision_score"] = raw_vision_scores # add a column for geo scores - InatInferrer.add_geo_score_column(leaf_scores, raw_geo_scores, "geo_score") - geo_column_for_scoring = "normalized_geo_score" - InatInferrer.add_geo_score_column( - leaf_scores, raw_raster_geo_scores, "raster_geo_score" + leaf_scores = InatInferrer.add_geo_score_column( + leaf_scores, raw_geo_scores, "geo_score", self ) + geo_column_for_scoring = "normalized_geo_score" if raw_raster_geo_scores is not None: # when raster geo scores are present, use them for calculating combined score geo_column_for_scoring = "normalized_raster_geo_score" @@ -385,10 +685,42 @@ def map_result_synonyms(self, leaf_scores, debug=False): print("Synonym Mapping Time: %0.2fms" % ((time.time() - start_time) * 1000.)) return leaf_scores + def restrict_results(self, all_scores, debug=False, + score_ratio_cutoff=0.001, + max_leaf_scores_to_consider=None, + column_for_cutoff="combined_score"): + top_combined_score = all_scores[column_for_cutoff].max() + + # define some cutoff based on a percentage of the top combined score. Taxa with + # scores below the cutoff will be ignored when aggregating scores up the taxonomy + cutoff = top_combined_score * score_ratio_cutoff + + # restrict score aggregation to results where the combined score is above the cutoff + restricted_results = all_scores.query( + f"{column_for_cutoff} > {cutoff}" + ) + + if max_leaf_scores_to_consider is not None: + restricted_results = restricted_results.sort_values( + column_for_cutoff, ascending=False + ).head(max_leaf_scores_to_consider) + + return restricted_results + def aggregate_results(self, leaf_scores, debug=False, score_ratio_cutoff=0.001, max_leaf_scores_to_consider=None, column_for_cutoff="combined_score"): + if self.new_scoring: + # print("USING NEW SCORING FOR aggregate_results") + return self.aggregate_results_new_scoring( + leaf_scores, + debug=debug, + score_ratio_cutoff=score_ratio_cutoff, + max_leaf_scores_to_consider=max_leaf_scores_to_consider, + column_for_cutoff=column_for_cutoff + ) + if debug: start_time = time.time() @@ -398,7 +730,7 @@ def aggregate_results(self, leaf_scores, debug=False, # copy columns from the already calculated leaf scores including scores # and class_id columns which will not be populated for synonyms in the taxonomy columns_to_copy = [ - "taxon_id", "vision_score", "normalized_vision_score", "geo_score", "raster_geo_score", + "taxon_id", "vision_score", "normalized_vision_score", "geo_score", "combined_score", "normalized_geo_score", "leaf_class_id", "iconic_class_id", "spatial_class_id" ] @@ -410,31 +742,17 @@ def aggregate_results(self, leaf_scores, debug=False, suffixes=["_x", None] ).set_index("taxon_id", drop=False) - # calculate the highest combined score from leaf_scores - top_combined_score = leaf_scores.sort_values( - column_for_cutoff, ascending=False - ).head(1)[column_for_cutoff].values[0] - # define some cutoff based on a percentage of the top combined score. Taxa with - # scores below the cutoff will be ignored when aggregating scores up the taxonomy - cutoff = top_combined_score * score_ratio_cutoff - - # restrict score aggregation to results where the combined score is above the cutoff - scores_to_aggregate = leaf_scores.query( - f"{column_for_cutoff} > {cutoff}" + scores_to_aggregate = self.restrict_results( + leaf_scores, debug, score_ratio_cutoff, max_leaf_scores_to_consider, column_for_cutoff ) - if max_leaf_scores_to_consider is not None: - scores_to_aggregate = scores_to_aggregate.sort_values( - column_for_cutoff, ascending=False - ).head(max_leaf_scores_to_consider) # loop through all results where the combined score is above the cutoff aggregated_scores = {} for taxon_id, vision_score, geo_score, \ - raster_geo_score, combined_score, geo_threshold in zip( + combined_score, geo_threshold in zip( scores_to_aggregate["taxon_id"], scores_to_aggregate["normalized_vision_score"], scores_to_aggregate["geo_score"], - scores_to_aggregate["raster_geo_score"], scores_to_aggregate["combined_score"], scores_to_aggregate["geo_threshold"]): # loop through the pre-calculated ancestors of this result's taxon @@ -445,7 +763,6 @@ def aggregate_results(self, leaf_scores, debug=False, aggregated_scores[ancestor_taxon_id]["aggregated_vision_score"] = 0 aggregated_scores[ancestor_taxon_id]["aggregated_combined_score"] = 0 aggregated_scores[ancestor_taxon_id]["aggregated_geo_score"] = 0 - aggregated_scores[ancestor_taxon_id]["aggregated_raster_geo_score"] = 0 aggregated_scores[ancestor_taxon_id][ "aggregated_geo_threshold" ] = geo_threshold if (ancestor_taxon_id == taxon_id) else 1.0 @@ -458,10 +775,6 @@ def aggregate_results(self, leaf_scores, debug=False, aggregated_scores[ancestor_taxon_id][ "aggregated_geo_score" ] = geo_score - if geo_score > aggregated_scores[ancestor_taxon_id]["aggregated_raster_geo_score"]: - aggregated_scores[ancestor_taxon_id][ - "aggregated_raster_geo_score" - ] = raster_geo_score # aggregated geo threshold is the min of descendant geo thresholds if ancestor_taxon_id != taxon_id and geo_threshold < aggregated_scores[ @@ -488,11 +801,139 @@ def aggregate_results(self, leaf_scores, debug=False, all_node_scores["normalized_aggregated_combined_score"] = all_node_scores[ "aggregated_combined_score"] / sum_of_root_node_aggregated_combined_scores + all_node_scores["normalized_geo_score"] = all_node_scores["normalized_geo_score"].fillna(0) if debug: print("Aggregation Time: %0.2fms" % ((time.time() - start_time) * 1000.)) # InatInferrer.print_aggregated_scores(all_node_scores) return all_node_scores + def aggregate_results_new_scoring(self, leaf_scores, debug=False, + score_ratio_cutoff=0.001, + max_leaf_scores_to_consider=None, + column_for_cutoff="combined_score"): + if self.innernode_scoring: + # print("USING INNERNODE SCORING FOR aggregate_results_new_scoring_innernode") + return self.aggregate_results_new_scoring_innernode( + leaf_scores, + debug=debug, + score_ratio_cutoff=score_ratio_cutoff, + max_leaf_scores_to_consider=max_leaf_scores_to_consider, + column_for_cutoff=column_for_cutoff + ) + + if debug: + start_time = time.time() + scores_to_aggregate = self.restrict_results( + leaf_scores.query("leaf_class_id.notnull() and vision_score > 0"), debug, + score_ratio_cutoff, max_leaf_scores_to_consider, column_for_cutoff + ) + + positions = np.asarray(scores_to_aggregate["spatial_class_id"], dtype=np.int32) + vision_scores = self.taxonomy_length_zeros() + combined_scores = self.taxonomy_length_zeros() + geo_scores = self.taxonomy_length_zeros() + geo_thresholds = self.taxonomy_length_nan() + vision_scores[positions] = leaf_scores["normalized_vision_score"][positions] + combined_scores[positions] = leaf_scores["combined_score"][positions] + geo_scores[positions] = leaf_scores["geo_score"][positions] + geo_thresholds[positions] = leaf_scores["geo_threshold"][positions] + + aggregate_taxonomy_up_inplace( + self.taxonomy.aggregation_index.parent_position, + self.taxonomy.aggregation_index.postorder, + min_arrays=(geo_thresholds,), + max_arrays=(geo_scores,), + sum_arrays=( + vision_scores, + combined_scores + ) + ) + + leaf_scores = leaf_scores.copy(deep=False) + leaf_scores["aggregated_vision_score"] = vision_scores + leaf_scores["aggregated_combined_score"] = combined_scores + leaf_scores["aggregated_geo_score"] = geo_scores + leaf_scores["aggregated_geo_threshold"] = geo_thresholds + + if debug: + print("aggregate_results_new_scoring: %0.2fms" % ((time.time() - start_time) * 1000.)) + start_time = time.time() + + sum_of_root_node_aggregated_vision_scores = leaf_scores.query( + "parent_taxon_id.isnull()")["aggregated_vision_score"].sum() + leaf_scores["normalized_aggregated_vision_score"] = leaf_scores[ + "aggregated_vision_score"] / sum_of_root_node_aggregated_vision_scores + sum_of_root_node_aggregated_combined_scores = leaf_scores.query( + "parent_taxon_id.isnull()")["aggregated_combined_score"].sum() + leaf_scores["normalized_aggregated_combined_score"] = leaf_scores[ + "aggregated_combined_score"] / sum_of_root_node_aggregated_combined_scores + + if debug: + print("aggregate_results_new_scoring normalization: %0.2fms" % ((time.time() - start_time) * 1000.)) + return leaf_scores + + def aggregate_results_new_scoring_innernode(self, leaf_scores, debug=False, + score_ratio_cutoff=0.001, + max_leaf_scores_to_consider=None, + column_for_cutoff="combined_score"): + if debug: + start_time = time.time() + scores_to_aggregate = self.restrict_results( + leaf_scores.query("leaf_class_id.notnull() and vision_score > 0"), debug, + score_ratio_cutoff, max_leaf_scores_to_consider, column_for_cutoff + ) + + positions = np.asarray(scores_to_aggregate["spatial_class_id"], dtype=np.int32) + vision_scores = self.taxonomy_length_zeros() + combined_scores = self.taxonomy_length_zeros() + dggd_combined_scores = self.taxonomy_length_zeros() + vision_scores[positions] = leaf_scores["normalized_vision_score"][positions] + combined_scores[positions] = leaf_scores["combined_score"][positions] + dggd_combined_scores[positions] = leaf_scores["dggd_combined"][positions] + + aggregate_taxonomy_up_inplace( + self.taxonomy.aggregation_index.parent_position, + self.taxonomy.aggregation_index.postorder, + min_arrays=(), + max_arrays=(), + sum_arrays=( + vision_scores, + combined_scores, + dggd_combined_scores + ) + ) + + if debug: + print("aggregate_results_new_scoring: %0.2fms" % ((time.time() - start_time) * 1000.)) + start_time = time.time() + + leaf_scores = leaf_scores.copy(deep=False) + leaf_scores["aggregated_vision_score"] = vision_scores + leaf_scores["aggregated_combined_score"] = combined_scores + leaf_scores["aggregated_geo_score"] = leaf_scores["geo_score"] + leaf_scores["aggregated_geo_threshold"] = leaf_scores["geo_threshold"] + leaf_scores["dggd_combined_aggregated"] = dggd_combined_scores + + sum_of_genus_diff_combined = leaf_scores.query("leaf_class_id.notnull()")["dggd_combined_aggregated"].sum() + leaf_scores["dggd_combined_normalized"] = leaf_scores["dggd_combined_aggregated"] / sum_of_genus_diff_combined + normalized_combined_score_post_geo = combined_scores / sum_of_genus_diff_combined + # As with the original scoring, taxa below genus retain their original combined scores, + # re-normalized. Genera and above use the dggd_combined scores with enhanced weight + leaf_scores["normalized_aggregated_combined_score"] = np.where( + leaf_scores["rank_level"] < 20, + normalized_combined_score_post_geo, + leaf_scores["dggd_combined_normalized"], + ) + + sum_of_root_node_aggregated_vision_scores = leaf_scores.query( + "parent_taxon_id.isnull()")["aggregated_vision_score"].sum() + leaf_scores["normalized_aggregated_vision_score"] = leaf_scores[ + "aggregated_vision_score"] / sum_of_root_node_aggregated_vision_scores + + if debug: + print("aggregate_results_new_scoring normalization: %0.2fms" % ((time.time() - start_time) * 1000.)) + return leaf_scores + def h3_04_geo_results_for_taxon_and_cell(self, taxon_id, lat, lng): if lat is None or lng is None: return None @@ -695,6 +1136,7 @@ def limit_leaf_scores_that_include_humans(self, leaf_scores, strategy=None): ) # if there is only 1 Mammals taxon (human), return all non-human results if mammals_results.index.size == 1: + # TODO: check if this should use leaf_scores, not top_results non_human_results = top_results.query( f"taxon_id != {self.taxonomy.human_taxon['taxon_id']}" ) @@ -815,12 +1257,22 @@ async def download_photo_async(self, url, session): return cache_path @staticmethod - def add_geo_score_column(dataframe, raw_geo_scores, column_name="geo_score"): + def add_geo_score_column(dataframe, raw_geo_scores, column_name="geo_score", inferrer=None): no_geo_scores = (raw_geo_scores is None) # add a column for geo scores if column_name in dataframe.columns: dataframe.drop(column_name, axis=1) - dataframe[column_name] = 0 if no_geo_scores else raw_geo_scores + if no_geo_scores: + dataframe[column_name] = 0 + elif inferrer.innernode_geomodel: + spatial_scores = inferrer.taxonomy.spatial_df.copy() + spatial_scores["geo_score"] = raw_geo_scores + dataframe = pd.merge(spatial_scores, + dataframe[["taxon_id", "vision_score"]], + on="taxon_id", + how="outer") + else: + dataframe[column_name] = raw_geo_scores # set a lower limit for geo scores if there are any normalized_column_name = f"normalized_{column_name}" @@ -828,6 +1280,7 @@ def add_geo_score_column(dataframe, raw_geo_scores, column_name="geo_score"): dataframe.drop(normalized_column_name, axis=1) dataframe[normalized_column_name] = 0 if no_geo_scores \ else dataframe[column_name].clip(InatInferrer.MINIMUM_GEO_SCORE, None) + return dataframe @staticmethod def prepare_image_for_inference(file_path): @@ -886,10 +1339,10 @@ def filter_geo_dataframe_by_bounds(geo_df, bounds): # similarly, the centroid may be on the other side of the antimedirian, so lookup # cells that might be just over the antimeridian on either side antimedirian_condition = "" - if bounds[1] < -179: - antimedirian_condition = "or (lng > 179)" - elif bounds[3] > 179: - antimedirian_condition = "or (lng < -179)" + if bounds[1] < -178: + antimedirian_condition = "or (lng > 178)" + elif bounds[3] > 178: + antimedirian_condition = "or (lng < -178)" # query for cells wtihin the buffered bounds, and potentially # on the other side of the antimeridian @@ -915,3 +1368,18 @@ def print_aggregated_scores(aggregated_scores): f"NC:{round(row.normalized_aggregated_combined_score, 4)}]" )) print("") + + def print_aggregated_scores_new_aggregation(aggregated_scores): + thresholded_results = aggregated_scores.query( + "combined_score > 0.00005" + ) + print("\nTree of aggregated results:") + ModelTaxonomyDataframe.print(thresholded_results, display_taxon_lambda=( + lambda row: f"{row.name} [" + f"ID:{row.taxon_id}, " + f"NV:{round(row.normalized_vision_score, 4)}, " + f"G:{round(row.geo_score, 4)}, " + f"GT:{round(row.geo_threshold, 4)}, " + f"NC:{round(row.normalized_combined_score, 4)}]" + )) + print("") diff --git a/lib/inat_vision_api.py b/lib/inat_vision_api.py index 4422c81..7a34cfb 100644 --- a/lib/inat_vision_api.py +++ b/lib/inat_vision_api.py @@ -155,17 +155,23 @@ def index_route(self): def score_image(self, form, file_path, lat, lng, filter_taxon_id, geomodel, common_ancestor_rank_type=None): + if self.debug: + start_time = time.time() filter_taxon = None if filter_taxon_id is not None: if self.inferrer.taxon_exists(filter_taxon_id): filter_taxon = self.inferrer.lookup_taxon(filter_taxon_id) else: filter_taxon = ModelTaxonomyDataframe.undefined_filter_taxon() + predictions_for_image = self.inferrer.predictions_for_image( file_path, lat, lng, filter_taxon, debug=self.debug ) leaf_scores = predictions_for_image["combined_scores"] + if self.debug: + print("score_image Time: %0.2fms" % ((time.time() - start_time) * 1000.)) + if form.aggregated.data == "true": aggregated_scores = self.inferrer.aggregate_results(leaf_scores, debug=self.debug) if form.format.data == "tree": @@ -173,11 +179,14 @@ def score_image(self, form, file_path, lat, lng, filter_taxon_id, geomodel, aggregated_scores, self.inferrer ) embedding = predictions_for_image["features"] - return InatVisionAPIResponses.aggregated_object_response( + response = InatVisionAPIResponses.aggregated_object_response( leaf_scores, aggregated_scores, self.inferrer, embedding=embedding, human_exclusion_strategy=form.human_exclusion.data ) + if self.debug: + print("total Time: %0.2fms" % ((time.time() - start_time) * 1000.)) + return response # legacy dict response if geomodel != "true": @@ -185,7 +194,7 @@ def score_image(self, form, file_path, lat, lng, filter_taxon_id, geomodel, if form.format.data == "object": embedding = predictions_for_image["features"] - return InatVisionAPIResponses.object_response( + response = InatVisionAPIResponses.object_response( leaf_scores, self.inferrer, common_ancestor_rank_type=common_ancestor_rank_type, @@ -193,6 +202,9 @@ def score_image(self, form, file_path, lat, lng, filter_taxon_id, geomodel, human_exclusion_strategy=form.human_exclusion.data, debug=self.debug ) + if self.debug: + print("total Time: %0.2fms" % ((time.time() - start_time) * 1000.)) + return response return InatVisionAPIResponses.array_response(leaf_scores, self.inferrer) @@ -223,8 +235,12 @@ def download_observation(self, observation_id, image_uuid): latlng = [None, None] else: latlng = data["results"][0]["location"].split(",") + if data["results"][0]["taxon"] is None: + iconic_taxon_id = None + else: + iconic_taxon_id = data["results"][0]["taxon"]["iconic_taxon_id"] # return the path to the cached image, coordinates, and iconic taxon - return cache_path, latlng[0], latlng[1], data["results"][0]["taxon"]["iconic_taxon_id"] + return cache_path, latlng[0], latlng[1], iconic_taxon_id def valid_leaf_taxon_id_for_request(self, request): if "taxon_id" in request.args: diff --git a/lib/inat_vision_api_responses.py b/lib/inat_vision_api_responses.py index 96b7ae0..efc7351 100644 --- a/lib/inat_vision_api_responses.py +++ b/lib/inat_vision_api_responses.py @@ -1,3 +1,4 @@ +import time import numpy as np import pandas as pd from lib.model_taxonomy_dataframe import ModelTaxonomyDataframe @@ -20,10 +21,17 @@ def array_response(leaf_scores, inferrer): return InatVisionAPIResponses.array_response_columns(leaf_scores).to_dict(orient="records") @staticmethod - def object_response(leaf_scores, inferrer, common_ancestor_rank_type=None, + def object_response(all_scores, inferrer, common_ancestor_rank_type=None, embedding=None, debug=False, human_exclusion_strategy=None): + + if debug: + start_time = time.time() + leaf_scores = all_scores.query("leaf_class_id.notnull() and vision_score > 0") leaf_scores = InatVisionAPIResponses.limit_leaf_scores_for_response(leaf_scores) leaf_scores = InatVisionAPIResponses.update_leaf_scores_scaling(leaf_scores) + if debug: + print("object_response update_scaling: %0.2fms" % ((time.time() - start_time) * 1000.)) + start_time = time.time() post_human_exclusion_scores = inferrer.limit_leaf_scores_that_include_humans( leaf_scores, strategy=human_exclusion_strategy @@ -32,15 +40,21 @@ def object_response(leaf_scores, inferrer, common_ancestor_rank_type=None, if not leaf_scores.empty and post_human_exclusion_scores.empty: human_exclusion_cleared_results = True leaf_scores = post_human_exclusion_scores + results = InatVisionAPIResponses.array_response_columns( leaf_scores.sort_values( "combined_score", ascending=False ).head(10) ).to_dict(orient="records") + if inferrer.new_scoring: + all_scores = InatVisionAPIResponses.update_leaf_scores_scaling(all_scores) common_ancestor = inferrer.common_ancestor_from_leaf_scores( - leaf_scores, common_ancestor_rank_type=common_ancestor_rank_type, debug=debug + all_scores, common_ancestor_rank_type=common_ancestor_rank_type, debug=debug ) + if debug: + print("object_response common_ancestor: %0.2fms" % ((time.time() - start_time) * 1000.)) + start_time = time.time() if common_ancestor is not None: common_ancestor_frame = pd.DataFrame([common_ancestor]) common_ancestor_frame = InatVisionAPIResponses.update_common_ancestor_scores_scaling( @@ -57,6 +71,9 @@ def object_response(leaf_scores, inferrer, common_ancestor_rank_type=None, } if embedding is not None: response["embedding"] = embedding.numpy().tolist() + if debug: + print("object_response remainder: %0.2fms" % ((time.time() - start_time) * 1000.)) + start_time = time.time() return response @staticmethod @@ -127,6 +144,7 @@ def aggregated_object_response( common_ancestor = inferrer.common_ancestor_from_leaf_scores( leaf_scores, debug=True, disallow_humans=True) + if common_ancestor is not None: common_ancestor_frame = pd.DataFrame([common_ancestor]) common_ancestor_frame = InatVisionAPIResponses.update_aggregated_scores_scaling( @@ -148,10 +166,7 @@ def aggregated_object_response( def limit_leaf_scores_for_response(leaf_scores): if leaf_scores.empty: return leaf_scores - top_combined_score = leaf_scores.sort_values( - "combined_score", - ascending=False - ).head(1)["combined_score"].values[0] + top_combined_score = leaf_scores["combined_score"].max() # set a cutoff so results whose combined scores are # much lower than the best score are not returned leaf_scores = leaf_scores.query(f"combined_score > {top_combined_score * 0.001}") @@ -162,7 +177,6 @@ def update_leaf_scores_scaling(leaf_scores): score_columns = [ "normalized_combined_score", "geo_score", - "raster_geo_score", "normalized_vision_score", "geo_threshold" ] @@ -187,9 +201,9 @@ def update_aggregated_scores_scaling(aggregated_scores): "aggregated_combined_score", "normalized_aggregated_combined_score", "aggregated_geo_score", - "aggregated_raster_geo_score", "aggregated_vision_score", - "aggregated_geo_threshold" + "aggregated_geo_threshold", + "normalized_geo_score" ] aggregated_scores[score_columns] = aggregated_scores[ score_columns @@ -201,7 +215,6 @@ def array_response_columns(leaf_scores): columns_to_return = [ "normalized_combined_score", "geo_score", - "raster_geo_score", "taxon_id", "name", "normalized_vision_score", @@ -239,7 +252,6 @@ def aggregated_scores_response_columns(aggregated_scores): "aggregated_combined_score", "normalized_aggregated_combined_score", "aggregated_geo_score", - "aggregated_raster_geo_score", "taxon_id", "parent_taxon_id", "name", @@ -249,6 +261,7 @@ def aggregated_scores_response_columns(aggregated_scores): "depth", "aggregated_vision_score", "aggregated_geo_threshold", + "normalized_geo_score" ] column_mapping = { "taxon_id": "id", @@ -256,7 +269,6 @@ def aggregated_scores_response_columns(aggregated_scores): "aggregated_combined_score": "combined_score", "normalized_aggregated_combined_score": "normalized_combined_score", "aggregated_geo_score": "geo_score", - "aggregated_raster_geo_score": "raster_geo_score", "aggregated_vision_score": "vision_score", "aggregated_geo_threshold": "geo_threshold" } diff --git a/lib/model_taxonomy_dataframe.py b/lib/model_taxonomy_dataframe.py index 78839a1..4ba70bc 100644 --- a/lib/model_taxonomy_dataframe.py +++ b/lib/model_taxonomy_dataframe.py @@ -1,5 +1,9 @@ import pandas as pd import math +import numba +import numpy as np + +from dataclasses import dataclass class ModelTaxonomyDataframe: @@ -49,10 +53,18 @@ def load_mapping(self, path, thresholds_path): self.df = self.df.join(thresholds) self.df["geo_threshold"] = self.df["geo_threshold"].fillna(1) + self.aggregation_index = build_taxonomy_aggregation_index( + self.df, + left_column="left", + ) + # create a data frame with just the leaf taxa using leaf_class_id as the index self.leaf_df = self.df.query("leaf_class_id.notnull()").set_index( "leaf_class_id", drop=False).sort_index() + self.spatial_df = self.df.query("spatial_class_id.notnull()").set_index( + "spatial_class_id", drop=False).sort_index() + # calculate nested set left and right values. These can be later used for an efficient # way to calculate if a taxon is an ancestor or descendant of another def assign_nested_values(self, taxon_id=0, index=0, depth=0, ancestor_taxon_ids=[]): @@ -111,6 +123,8 @@ def printable_tree(df, taxon_id=0, ancestor_prefix="", display_taxon_lambda=None index = 0 if "aggregated_combined_score" in children: children = children.sort_values("aggregated_combined_score", ascending=False) + elif "normalized_combined_score" in children: + children = children.sort_values("normalized_combined_score", ascending=False) else: children = children.sort_values("name") linesToPrint = [] @@ -146,3 +160,182 @@ def undefined_filter_taxon(): "left": 0, "right": 0 } + + +@dataclass(frozen=True) +class TaxonomyAggregationIndex: + # Indexed by spatial_class_id: + parent_position: np.ndarray + # All nodes, children before parents: + postorder: np.ndarray + # All nodes, parents before children: + preorder: np.ndarray + + +def build_taxonomy_aggregation_index( + taxonomy: pd.DataFrame, + *, + id_column: str = "taxon_id", + parent_id_column: str = "parent_taxon_id", + spatial_class_id_column: str = "spatial_class_id", + left_column: str = "left", +) -> TaxonomyAggregationIndex: + """ + Build dense tree arrays where every array position is spatial_class_id. + + Assumptions: + - spatial_class_id is unique + - spatial_class_id contains every integer from 0 through N - 1 + - parent_id_column refers to taxon IDs, not spatial_class_ids + - descending nested-set left order processes descendants before ancestors + """ + node_count = len(taxonomy) + + spatial_class_ids = taxonomy[ + spatial_class_id_column + ].to_numpy(dtype=np.int64, copy=False) + + if taxonomy[spatial_class_id_column].isna().any(): + raise ValueError( + f"{spatial_class_id_column} cannot contain null values" + ) + + if taxonomy[spatial_class_id_column].duplicated().any(): + raise ValueError( + f"{spatial_class_id_column} must be unique" + ) + + # Since raw_scores[i] represents spatial_class_id i, IDs must be dense. + expected_ids = np.arange(node_count, dtype=np.int64) + + if not np.array_equal(np.sort(spatial_class_ids), expected_ids): + raise ValueError( + f"{spatial_class_id_column} must contain every integer " + f"from 0 through {node_count - 1}" + ) + + if taxonomy[id_column].duplicated().any(): + raise ValueError(f"{id_column} must be unique") + + # Map taxon_id -> spatial_class_id. This is only needed during setup. + taxon_id_to_position = pd.Series( + spatial_class_ids, + index=taxonomy[id_column], + ) + + # Arrays are indexed directly by spatial_class_id. + parent_position = np.full( + node_count, + -1, + dtype=np.int32, + ) + + has_parent = taxonomy[parent_id_column].notna() + + parent_positions = taxon_id_to_position.reindex( + taxonomy.loc[has_parent, parent_id_column] + ) + + if parent_positions.isna().any(): + missing_parent_ids = ( + taxonomy.loc[has_parent, parent_id_column] + .loc[parent_positions.isna().to_numpy()] + .unique() + ) + + raise ValueError( + "Parent taxon IDs are missing from the taxonomy: " + f"{missing_parent_ids[:10]}" + ) + + child_positions = taxonomy.loc[ + has_parent, + spatial_class_id_column, + ].to_numpy(dtype=np.int64, copy=False) + + parent_position[child_positions] = parent_positions.to_numpy( + dtype=np.int32, + ) + + left_values = taxonomy[left_column].to_numpy( + dtype=np.int64, + copy=False, + ) + + preorder_row_indices = np.argsort( + left_values, + kind="stable", + ) + + preorder = spatial_class_ids[ + preorder_row_indices + ].astype( + np.int32, + copy=False, + ) + + postorder = preorder[::-1].copy() + + return TaxonomyAggregationIndex( + parent_position=parent_position, + postorder=postorder, + preorder=preorder + ) + + +@numba.njit(cache=True, nogil=True) +def aggregate_taxonomy_up_inplace( + parent_position: np.ndarray, + postorder: np.ndarray, + min_arrays: tuple, + max_arrays: tuple, + sum_arrays: tuple, +) -> None: + """ + Aggregate each array over the node itself and all descendants. + + Arrays must be writable and indexed by spatial_class_id. + Pass () for unused aggregation types. + """ + for order_index in range(postorder.size): + node = postorder[order_index] + parent = parent_position[node] + + if parent < 0: + continue + + if len(min_arrays) > 0: + for min_values in min_arrays: + if (np.isnan(min_values[parent]) or min_values[node] < min_values[parent]): + min_values[parent] = min_values[node] + + if len(max_arrays) > 0: + for max_values in max_arrays: + if max_values[node] > max_values[parent]: + max_values[parent] = max_values[node] + + if len(sum_arrays) > 0: + for sum_values in sum_arrays: + sum_values[parent] += sum_values[node] + + +@numba.njit(cache=True, nogil=True) +def propagate_max_down_tree_inplace( + scores: np.ndarray, + parent_position: np.ndarray, + preorder: np.ndarray, +) -> None: + """ + Afterward: + + scores[node] = max( + raw score at node, + raw scores of all ancestors + ) + """ + for order_index in range(preorder.size): + node = preorder[order_index] + parent = parent_position[node] + + if parent >= 0 and scores[parent] > scores[node]: + scores[node] = scores[parent] diff --git a/lib/vision_inferrer.py b/lib/vision_inferrer.py index 973fcab..e5e35b5 100644 --- a/lib/vision_inferrer.py +++ b/lib/vision_inferrer.py @@ -1,4 +1,5 @@ import tensorflow as tf +import numpy as np class VisionInferrer: @@ -56,7 +57,7 @@ def prepare_tf_model(self): def process_image(self, image): layer_results = self.infer(image) return { - "predictions": layer_results[0][0], + "predictions": np.asarray(layer_results[0][0], dtype=np.float32), "features": layer_results[1][0], } diff --git a/lib/vision_testing.py b/lib/vision_testing.py index 7c96863..060b1a5 100644 --- a/lib/vision_testing.py +++ b/lib/vision_testing.py @@ -218,9 +218,13 @@ def display_and_save_results(self, label): agg_stats = all_obs_scores_df.groupby("run_label").agg( average_results_count=("results_count", "mean"), common_ancestor_pool_size=("common_ancestor_pool_size", "mean"), + average_top_score=("top_score", "mean"), + average_matching_score=("matching_score", "mean"), + average_common_ancestor_score=("common_ancestor_score", "mean"), precision=("precision", "mean"), recall=("recall", "mean"), - f1=("f1", "mean") + f1=("f1", "mean"), + run_time=("run_time", "mean") ) grouped_stats = grouped_stats.merge( agg_stats, how="left", left_on="run_label", right_on="run_label" @@ -229,9 +233,19 @@ def display_and_save_results(self, label): grouped_stats["common_ancestor_pool_size"] = grouped_stats[ "common_ancestor_pool_size" ].round(4) + grouped_stats["average_top_score"] = grouped_stats[ + "average_top_score" + ].round(4) + grouped_stats["average_matching_score"] = grouped_stats[ + "average_matching_score" + ].round(4) + grouped_stats["average_common_ancestor_score"] = grouped_stats[ + "average_common_ancestor_score" + ].round(4) grouped_stats["precision"] = grouped_stats["precision"].round(4) grouped_stats["recall"] = grouped_stats["recall"].round(4) grouped_stats["f1"] = grouped_stats["f1"].round(4) + grouped_stats["run_time"] = grouped_stats["run_time"].round(4) grouped_stats["nearby%"] = round( (grouped_stats["nearby"] / grouped_stats["count"]) * 100, 2 ) @@ -271,6 +285,7 @@ async def test_observation_async(self, observation): lng = observation.lng try: # traditional leaf combined scores, vision * geo + start_time = time.time() predictions_for_image = inferrer.predictions_for_image( cache_path, lat, lng, filter_taxon ) @@ -279,17 +294,18 @@ async def test_observation_async(self, observation): inferrer_results[inferrer_index] = self.inferrer_results( inferrer, observation, leaf_scores ) + run_time = (time.time() - start_time) * 1000. # summarize that high-level data further into the metrics we ultimately want summaries = {} for summary_index, summary in inferrer_results[inferrer_index].items(): summaries[summary_index] = self.summarize_result_subset( - inferrer, observation, summary, summary_index) + inferrer, observation, summary, summary_index, run_time) # the "cutoff" variant limits the top100 retults into the subset users might # actually be presented. That means removing results with a score less than # 0.001 times the top score, and using up to 10 of those. This will give values # for precision, recall, f1 relative to user experience rather than all results summaries[f"{summary_index}-cutoff"] = self.summarize_result_subset( - inferrer, observation, summary, summary_index, cutoff=True + inferrer, observation, summary, summary_index, run_time, cutoff=True ) summarized_results[inferrer_index] = summaries @@ -330,6 +346,7 @@ def inferrer_results(self, inferrer, observation, leaf_scores): combined_aggregated_scores, score_to_use="combined_score" ) + leaf_scores = leaf_scores.query("leaf_class_id.notnull()") # record the top 100 scores of 3 score types: vision only, combined, and combined + nearby vision_top_100 = leaf_scores.sort_values( "vision_score", ascending=False @@ -340,7 +357,7 @@ def inferrer_results(self, inferrer, observation, leaf_scores): ).reset_index(drop=True).head(100) combined_nearby_top_100 = leaf_scores.query( - "geo_score >= geo_threshold" + "geo_score >= geo_threshold and combined_score > 0" ).sort_values( "combined_score", ascending=False ).reset_index(drop=True).head(100) @@ -379,11 +396,11 @@ def common_ancestor_score(self, common_ancestor): def common_ancestor_pool_size(self, aggregated_scores): return aggregated_scores.query( - "leaf_class_id.notnull()" + "leaf_class_id.notnull() and aggregated_vision_score > 0" ).index.size def summarize_result_subset( - self, inferrer, observation, inferrer_results, summary_index, cutoff=False + self, inferrer, observation, inferrer_results, summary_index, run_time, cutoff=False ): working_results = inferrer_results["scores"] score_column = "vision_score" if summary_index == "vision" else "combined_score" @@ -451,6 +468,8 @@ def summarize_result_subset( summary["match_nearby"] = 1 if matching_geo_threshold > 0 and \ matching_geo_score > matching_geo_threshold else 0 + summary["run_time"] = run_time + return summary def matching_index(self, observation, results): diff --git a/requirements.txt b/requirements.txt index c9b1365..7283f3a 100644 --- a/requirements.txt +++ b/requirements.txt @@ -15,6 +15,7 @@ pandas==2.1.2 pillow==10.3.0 pipenv==2023.12.1 prison==0.2.1 +pyarrow==21.0.0 python-magic==0.4.27 PyYAML==6.0.1 scikit-learn==1.4.1.post1