11#!/usr/bin/env python3
22# AUTHOR: Sirio Bolaños Puchet <[email protected] > 33# CREATION DATE: 2023-05-30
4- # LAST MODIFICATION: 2024-05-02
4+ # LAST MODIFICATION: 2024-05-13
55
66_PROGNAME = 'flatplot'
77
6868import colorcet
6969
7070
71- def flatplot (flatpos , flatval , cmap = colorcet .gray , flatpix = 256 , reduction = ds .max , how = 'linear' ,
72- span = (0 , 1 ), dual = False ):
71+ def flatplot (flatpos , flatval , cmap = colorcet .gray , flatpix = 256 , reduction = ds .max ,
72+ how = 'linear' , span = (0 , 1 ), dual = False ):
7373 import pandas as pd
74- plot_width = 2 * flatpix if dual else flatpix
75- x_range = ( 0 , 2 ) if dual else ( 0 , 1 )
76- cvs = ds .Canvas (plot_width = plot_width , plot_height = flatpix , x_range = x_range , y_range = (0 ,1 ))
77- df = pd .DataFrame (flatpos , columns = ('x' ,'y' ))
74+ x_range = ( 0 , 2 ) if dual else ( 0 , 1 )
75+ width = 2 * flatpix if dual else flatpix
76+ cvs = ds .Canvas (plot_width = width , plot_height = flatpix , x_range = x_range , y_range = (0 , 1 ))
77+ df = pd .DataFrame (flatpos , columns = ('x' , 'y' ))
7878 df ['val' ] = flatval # set column while keeping data type
79- agg = cvs .points (df ,'x' ,'y' ,reduction ('val' ))
79+ agg = cvs .points (df , 'x' , 'y' , reduction ('val' ))
8080 return tf .shade (agg , how = how , cmap = cmap , span = span ), agg
8181
8282
8383def flatplot_dots (flatpos , flatval , cmap = '#000000' , flatpix = 256 , how = 'eq_hist' , spread = None ,
8484 dual = False ):
8585 import pandas as pd
86- x_range = (0 ,2 ) if dual else (0 ,1 )
87- cvs = ds .Canvas (plot_width = flatpix , plot_height = flatpix , x_range = x_range , y_range = (0 ,1 ))
88- df = pd .DataFrame (flatpos , columns = ('x' ,'y' ))
89- agg = cvs .points (df ,'x' ,'y' )
86+ x_range = (0 , 2 ) if dual else (0 , 1 )
87+ width = 2 * flatpix if dual else flatpix
88+ cvs = ds .Canvas (plot_width = width , plot_height = flatpix , x_range = x_range , y_range = (0 , 1 ))
89+ df = pd .DataFrame (flatpos , columns = ('x' , 'y' ))
90+ agg = cvs .points (df , 'x' , 'y' )
9091 if spread is not None :
9192 return tf .shade (tf .spread (agg , px = spread ), cmap = cmap , how = how ), agg
9293 else :
@@ -98,7 +99,8 @@ def get_mode(vals):
9899 return x [np .argmax (c )]
99100
100101
101- def flatplot_regions (flatpos , flatval , cmap = colorcet .glasbey , flatpix = 256 , valbkg = - 1 ):
102+ def flatplot_regions (flatpos , flatval , cmap = colorcet .glasbey , flatpix = 256 , valbkg = - 1 ,
103+ dual = False ):
102104 from collections import defaultdict
103105 import xarray as xr
104106 try :
@@ -117,23 +119,25 @@ def flatplot_regions(flatpos, flatval, cmap=colorcet.glasbey, flatpix=256, valbk
117119 # compute mode of values per pixel
118120 d = defaultdict (list )
119121 for x , y , z in idat :
120- d [(x ,y )].append (z )
122+ d [(x , y )].append (z )
121123 if has_parallel :
122124 with parallel_config (backend = 'threading' , n_jobs = cpu_count ()):
123125 result = Parallel ()(delayed (get_mode )(v ) for v in d .values ())
124126 else :
125127 result = [get_mode (v ) for v in d .values ()]
126128 dmode = {k : result [i ] for i , k in enumerate (d .keys ())}
127129 # setup raster
128- arr = np .full ((flatpix ,flatpix ), np .nan , dtype = 'float32' )
129- for k ,v in dmode .items ():
130+ width = 2 * flatpix if dual else flatpix
131+ arr = np .full ((width , flatpix ), np .nan , dtype = 'float32' )
132+ for k , v in dmode .items ():
130133 arr [k ] = v
131134 # correct orientation
132135 arr = np .rot90 (np .flipud (arr ), - 1 )
133136 # plot
134- cvs = ds .Canvas (plot_width = flatpix , plot_height = flatpix )
135- xs = ys = np .linspace (0 , 1 , flatpix )
136- x = xr .DataArray (arr ,coords = [('y' , ys ), ('x' , xs )])
137+ cvs = ds .Canvas (plot_width = width , plot_height = flatpix )
138+ xs = np .linspace (0 , 1 , width )
139+ ys = np .linspace (0 , 1 , flatpix )
140+ x = xr .DataArray (arr , coords = [('y' , ys ), ('x' , xs )])
137141 agg = cvs .raster (x )
138142 return tf .shade (agg , how = 'linear' , cmap = cmap , span = (0 , len (cmap ) - 1 )), agg
139143
@@ -143,13 +147,13 @@ def str_to_reduction(s):
143147 return ds .max
144148 elif s in ['min' ]:
145149 return ds .min
146- elif s in ['avg' ,'mean' ]:
150+ elif s in ['avg' , 'mean' ]:
147151 return ds .mean
148152 elif s in ['sum' ]:
149153 return ds .sum
150154 elif s in ['mode' ]:
151155 return ds .mode
152- elif s in ['std' ,'sd' ]:
156+ elif s in ['std' , 'sd' ]:
153157 return ds .std
154158 elif s in ['var' ]:
155159 return ds .var
@@ -172,6 +176,7 @@ def str_to_reduction(s):
172176 if args .regions :
173177 func = flatplot_regions
174178 kwargs .update ({'valbkg' : args .regions_background })
179+ kwargs .update ({'dual' : args .dual })
175180 elif args .dots :
176181 func = flatplot_dots
177182 kwargs .update ({'spread' : args .spread })
@@ -185,6 +190,7 @@ def str_to_reduction(s):
185190 LOGGER .info ('Loading flat map "{}"' .format (args .flatmap ))
186191 fmap , fmap_valid = fmutil .load_flatmap (args .flatmap )
187192
193+ lay = None
188194 if args .dots :
189195 LOGGER .info ('Loading dots "{}"' .format (args .dataset ))
190196 dots = np .loadtxt (args .dataset )
@@ -203,13 +209,12 @@ def str_to_reduction(s):
203209
204210 data_valid = True
205211 if args .mask is not None :
206- LOGGER .info ('Loading data mask "{}"' .format (args .mask ))
212+ LOGGER .info ('Loading mask "{}"' .format (args .mask ))
207213 dmsk = VoxelData .load_nrrd (args .mask )
208214 assert (dmsk .shape == dat .shape )
209215 data_valid = (dmsk .raw != 0 )
210216 del dmsk
211217
212- lay = None
213218 if args .split or args .only_layer is not None :
214219 LOGGER .info ('Loading layer annotation "{}"' .format (args .layers ))
215220 lay = VoxelData .load_nrrd (args .layers )
@@ -225,17 +230,18 @@ def str_to_reduction(s):
225230 flatpos = fmap .raw [mask ]
226231 flatval = dat .raw [mask ]
227232
233+ img_w = 2 * args .flatpix if args .dual else args .flatpix
228234 if lay is not None :
229235 LOGGER .info ('Masking layer annotation' )
230236 layval = lay .raw [mask ]
231237 for k , v in ldict .items ():
232- LOGGER .info ('Generating and saving image for Layer {} ({}x{})' .format (v , args . flatpix , args .flatpix ))
238+ LOGGER .info ('Generating and saving image for Layer {} ({}x{})' .format (v , img_w , args .flatpix ))
233239 lmask = np .where (layval == k )
234240 img , agg = func (flatpos [lmask ], flatval [lmask ], cmap , args .flatpix , ** kwargs )
235241 LOGGER .info ('Min: {} Max: {}' .format (np .nanmin (agg .values ), np .nanmax (agg .values )))
236242 ds .utils .export_image (img , '{}_Layer{}' .format (args .output_prefix , v ), background = None , _return = False )
237243 else :
238- LOGGER .info ('Generating and saving image ({}x{})' .format (args . flatpix , args .flatpix ))
244+ LOGGER .info ('Generating and saving image ({}x{})' .format (img_w , args .flatpix ))
239245 img , agg = func (flatpos , flatval , cmap , args .flatpix , ** kwargs )
240246 LOGGER .info ('Min: {} Max: {}' .format (np .nanmin (agg .values ), np .nanmax (agg .values )))
241247 ds .utils .export_image (img , args .output_prefix , background = None , _return = False )
0 commit comments