@@ -743,7 +743,6 @@ def _set_color_source_vec(
743743 color = np .full (len (element ), value_to_plot )
744744 return None , color , False
745745
746- # Figure out where to get the color from
747746 origins = _locate_value (
748747 value_key = value_to_plot ,
749748 sdata = sdata ,
@@ -765,11 +764,9 @@ def _set_color_source_vec(
765764 table_layer = table_layer ,
766765 )[value_to_plot ]
767766
768- # Check what type of data we're dealing with
769767 is_categorical = isinstance (color_source_vector .dtype , pd .CategoricalDtype )
770768 is_numeric = pd .api .types .is_numeric_dtype (color_source_vector )
771769
772- # If it's numeric data, handle it appropriately
773770 if is_numeric and not is_categorical :
774771 if (
775772 not isinstance (element , GeoDataFrame )
@@ -784,7 +781,6 @@ def _set_color_source_vec(
784781 )
785782 return None , color_source_vector , False
786783
787- # For non-numeric, non-categorical data (like strings), convert to categorical
788784 if not is_categorical :
789785 try :
790786 color_source_vector = pd .Categorical (color_source_vector )
@@ -794,8 +790,6 @@ def _set_color_source_vec(
794790 return None , color_source_vector , False
795791
796792 # At this point color_source_vector should be categorical
797-
798- # Look for predefined colors in the AnnData object
799793 adata_with_colors = None
800794 cluster_key = value_to_plot
801795
@@ -812,12 +806,12 @@ def _set_color_source_vec(
812806 first_table = next (iter (annotator_tables ))
813807 adata_with_colors = sdata .tables [first_table ]
814808 adata_with_colors .uns ["spatialdata_key" ] = first_table
809+
815810 # If no specific table is found, try using the default table
816811 elif sdata .table is not None :
817812 adata_with_colors = sdata .table
818813 adata_with_colors .uns ["spatialdata_key" ] = "default_table"
819814
820- # Now generate the color mapping using the appropriate AnnData object and cluster_key
821815 color_mapping = _get_categorical_color_mapping (
822816 adata = adata_with_colors ,
823817 cluster_key = cluster_key ,
@@ -868,7 +862,6 @@ def _map_color_seg(
868862) -> ArrayLike :
869863 cell_id = np .array (cell_id )
870864
871- # Safely handle different types of color_vector
872865 is_categorical = pd .api .types .is_categorical_dtype (getattr (color_vector , "dtype" , None ))
873866 is_numeric = pd .api .types .is_numeric_dtype (getattr (color_vector , "dtype" , None ))
874867 is_pandas_series = isinstance (color_vector , pd .Series )
@@ -962,31 +955,26 @@ def _generate_base_categorial_color_mapping(
962955 na_color : ColorLike ,
963956 cmap_params : CmapParams | None = None ,
964957) -> Mapping [str , str ]:
965- color_key = f"{ cluster_key } _colors"
966958
967- # Break long string template into multiple lines to fix E501 error
959+ color_key = f" { cluster_key } _colors"
968960 color_found_in_uns_msg_template = (
969961 "Using colors from '{cluster}_colors' in .uns slot of table '{table}' for plotting. "
970962 "If this is unexpected, please delete the column from your AnnData object."
971963 )
972964
973- # Check if we have a valid AnnData and if the color key exists in uns
974965 if adata is not None and cluster_key is not None :
975- # Check for direct color dictionary in uns (e.g., {'A': '#FF5733', 'B': '#3498DB'})
976966 if cluster_key in adata .uns and isinstance (adata .uns [cluster_key ], dict ):
977967 # We have a direct color mapping dictionary
978968 color_dict = adata .uns [cluster_key ]
979969 table_name = getattr (adata , "uns" , {}).get ("spatialdata_key" , "" )
980970 if table_name :
981- # Format the template with the actual values
982971 logger .info (color_found_in_uns_msg_template .format (cluster = cluster_key , table = table_name ))
983972
984973 # Ensure all values are hex colors
985974 for k , v in color_dict .items ():
986975 if isinstance (v , str ) and not v .startswith ("#" ):
987976 color_dict [k ] = to_hex (to_rgba (v ))
988977
989- # Add NA color if missing
990978 categories = color_source_vector .categories .tolist ()
991979 na_color_hex = to_hex (to_rgba (na_color )[:3 ])
992980
@@ -996,24 +984,16 @@ def _generate_base_categorial_color_mapping(
996984 colors = adata .uns [color_key ]
997985 table_name = getattr (adata , "uns" , {}).get ("spatialdata_key" , "" )
998986 if table_name :
999- if isinstance (colors , dict ):
1000- # Format the template with the actual values
1001- logger .info (color_found_in_uns_msg_template .format (cluster = cluster_key , table = table_name ))
1002- else :
1003- # Format the template with the actual values
1004- logger .info (color_found_in_uns_msg_template .format (cluster = cluster_key , table = table_name ))
987+ logger .info (color_found_in_uns_msg_template .format (cluster = cluster_key , table = table_name ))
1005988
1006- # Ensure colors are in hex format
1007989 if isinstance (colors , list ):
1008990 colors = [to_hex (to_rgba (color )[:3 ]) for color in colors ]
1009991 categories = color_source_vector .categories .tolist ()
1010992
1011- # Handle NaN values
1012993 na_color_hex = to_hex (to_rgba (na_color )[:3 ])
1013994 if "NaN" not in categories :
1014995 categories .append ("NaN" )
1015996
1016- # Make sure we have enough colors
1017997 if len (colors ) < len (categories ) - 1 : # -1 for NaN
1018998 logger .warning (
1019999 f"Not enough colors in { color_key } ({ len (colors )} ) for all categories ({ len (categories ) - 1 } ). "
@@ -1022,39 +1002,31 @@ def _generate_base_categorial_color_mapping(
10221002 # Extend with default colors or duplicate the last color
10231003 colors .extend ([na_color_hex ] * (len (categories ) - 1 - len (colors )))
10241004
1025- # Create mapping with NaN color
10261005 return dict (zip (categories , colors + [na_color_hex ], strict = False ))
10271006
10281007 if isinstance (colors , np .ndarray ):
1029- # Convert numpy array to list of hex colors
10301008 colors = [to_hex (to_rgba (color )[:3 ]) for color in colors ]
10311009 categories = color_source_vector .categories .tolist ()
10321010
1033- # Handle NaN values
10341011 na_color_hex = to_hex (to_rgba (na_color )[:3 ])
10351012 if "NaN" not in categories :
10361013 categories .append ("NaN" )
10371014
1038- # Make sure we have enough colors
10391015 if len (colors ) < len (categories ) - 1 : # -1 for NaN
10401016 logger .warning (
10411017 f"Not enough colors in { color_key } ({ len (colors )} ) for all categories ({ len (categories ) - 1 } ). "
10421018 "Some categories will use default colors."
10431019 )
1044- # Extend with default colors
10451020 colors .extend ([na_color_hex ] * (len (categories ) - 1 - len (colors )))
10461021
1047- # Create mapping with NaN color
10481022 return dict (zip (categories , colors + [na_color_hex ], strict = False ))
10491023
1050- # Dictionary format - direct color mapping
10511024 if isinstance (colors , dict ):
10521025 # Ensure all values are hex colors
10531026 for k , v in colors .items ():
10541027 if isinstance (v , str ) and not v .startswith ("#" ):
10551028 colors [k ] = to_hex (to_rgba (v ))
10561029
1057- # Get categories and handle NaN
10581030 categories = color_source_vector .categories .tolist ()
10591031 na_color_hex = to_hex (to_rgba (na_color )[:3 ])
10601032
@@ -1072,8 +1044,6 @@ def _generate_base_categorial_color_mapping(
10721044
10731045 return result
10741046
1075- # If we reach here, we didn't find usable colors in uns, use default color mapping
1076- logger .info (f"No colors found for '{ cluster_key } ' in AnnData.uns, using default colors" )
10771047 return _get_default_categorial_color_mapping (color_source_vector = color_source_vector , cmap_params = cmap_params )
10781048
10791049
0 commit comments