code
stringlengths
1
18.2k
# Find the maxima. These are high-values with enough clearance # around them. # Work from high to low bins. The pixels in the highest bin mark their # neighborhoods first. If you did it from low to high the lowest maxima # would mark their neighborhoods first and interfere with the identification of higher maxima. for ...
with high intensity bins and gets smaller with low intensity bins. infl_dist = MIN_INFL + int(np.round(float(b) / self.max_bin * (MAX_INFL - MIN_INFL))) for p in pixels[b]: if marked[p] == self.UNMARKED: ok = False del marked_so_far[:] # Temporarily mark unmarked points in square around point (keep track of them in lis...
higher intensity center, # this counts as a new center and ok=True and points will remain marked. # Otherwise ok=False and marked points that were previously unmarked will be unmarked. for (i, j), v in np.ndenumerate(marked[p[0] - infl_dist:p[0] + infl_dist + 1, p[1] - infl_dist:p[1]+ infl_dist + 1]): if v == self.UNMA...
= b marked_so_far.append((i - infl_dist + p[0],j - infl_dist + p[1])) else: # neighborhood already taken ok = False break # ok if point and surrounding square were not marked already. if ok: # highest point in its neighborhood centers[b].append(p) else: for m in marked_so_far: marked[m] = self.UNMARKED # Erase marks an...
self.UNMARKED deferred_from_last = [] deferred_to_next = [] # delta (int): maximum number of increments the cluster is allowed to range over. Larger d results in clusters over larger scales. for delta in range(0, self.delta + 1): # Work from high to low bins. for b in sorted(centers.keys(), reverse=True): bin_lower = b...
tot_centers = n_centers + len(deferred_from_last) for i in range(tot_centers): # done this way to minimize memory overhead of maintaining two lists if i < n_centers: center = centers[b][i] else: center = deferred_from_last[i - n_centers] if bin_lower < 0: bin_lower = 0 if marked[center] == self.UNMARKED: captured = sel...
get big enough deferred_to_next.append(center) else: pass # this is the last one for this bin self.remove_foothills(q_data, marked, b, bin_lower, centers, foothills) del deferred_from_last[:] del deferred_to_next[:] return marked
def set_maximum(self, q_data, marked, center, bin_lower, foothills): """ Grow a region at a certain bin level and check if the region has reached the maximum size. Args: q_data: Quantized data array marked: Array marking points that are objects center: Coordinates of the center pixel of the region being grown bin_lower...
with a center but fall outside the the size or intensity criteria Returns: True if the object is finished growing and False if the object should be grown again at the next threshold level. """ as_bin = [] # pixels to be included in peak as_glob = [] # pixels to be globbed up as part of foothills marked_so_far = [] # pi...
have already been marked will_be_considered_again = False as_bin.append(center) center_data = q_data[center] while len(as_bin) > 0: p = as_bin.pop(-1) # remove and return last pixel in as_bin if marked[p] != self.UNMARKED: # already processed continue marked[p] = q_data[center] marked_so_far.append(p) # check neighbors...
if val == self.UNMARKED: pixel = (index[0] - 1 + p[0],index[1] - 1 + p[1]) p_data = q_data[pixel] if (not will_be_considered_again) and (p_data >= 0) and (p_data < center_data): will_be_considered_again = True if p_data >= bin_lower and (np.abs(center_data - p_data) <= self.delta): as_bin.append(pixel) # Do not check t...
0: as_glob.append(pixel) if bin_lower == 0: will_be_considered_again = False big_enough = len(marked_so_far) >= self.max_size if big_enough: # remove lower values within region of influence foothills.append((center, as_glob)) elif will_be_considered_again: # remove the check if you want to ignore regions smaller than m...
def remove_foothills(self, q_data, marked, bin_num, bin_lower, centers, foothills): """ Mark points determined to be foothills as globbed, so that they are not included in future searches. Also searches neighboring points to foothill points to determine if they should also be considered foothills. Args: q_data: Quantiz...
to be object centers foothills: List of foothill points being removed. """ hills = [] for foot in foothills: center = foot[0] hills[:] = foot[1][:] # remove all foothills while len(hills) > 0: # mark this point pt = hills.pop(-1) marked[pt] = self.GLOBBED for s_index, val in np.ndenumerate(marked[pt[0]-1:pt[0]+2,pt[1]-...
of peak or part of mountain? if val == self.UNMARKED: # will let in even minor peaks if (q_data[index] >= 0) and \ (q_data[index] < bin_lower) and \ ((q_data[index] <= q_data[pt]) or self.is_closest(index, center, centers, bin_num)): hills.append(index) del foothills[:]
def quantize(self, input_grid): """ Quantize a grid into discrete steps based on input parameters. Args: input_grid: 2-d array of values Returns: Dictionary of value pointing to pixel locations, and quantized 2-d array of data """ pixels = {} for i in range(self.max_bin+1): pixels[i] = [] data = (np.array(input_grid, d...
= np.where(data >= 0) for g in np.arange(good_points[0].shape[0]): pixels[data[(good_points[0][g], good_points[1][g])]].append((good_points[0][g], good_points[1][g])) return pixels, data
def listall(self): ''' will display all the filenames. Result can be stored in an array for easy fetching of gistNames for future purposes. eg. a = Gist().mygists().listall() print a[0] #to fetch first gistName ''' file_name = [] r = requests.get( '%s/users/%s/gists' % (BASE_URL, self.user), headers=self.gist.header ) ...
in r.json()[no]['files'].iteritems(): file_name.append(value['filename']) return file_name raise Exception('Username not found')
def content(self, **args): ''' Doesn't require manual fetching of gistID of a gist passing gistName will return the content of gist. In case, names are ambigious, provide GistID or it will return the contents of recent ambigious gistname ''' self.gist_name = '' if 'name' in args: self.gist_name = args['name'] self.gist...
user\'s Unambigious Gistname or any unique Gistid') if self.gist_id: r = requests.get( '%s'%BASE_URL+'/gists/%s' %self.gist_id, headers=self.gist.header ) if (r.status_code == 200): r_text = json.loads(r.text) if self.gist_name!='': content = r.json()['files'][self.gist_name]['content'] else: for key,value in r.json()[...
def edit(self, **args): ''' Doesn't require manual fetching of gistID of a gist passing gistName will return edit the gist ''' self.gist_name = '' if 'description' in args: self.description = args['description'] else: self.description = '' if 'name' in args and 'id' in args: self.gist_name = args['name'] self.gist_id =...
= args['id'] else: raise Exception('Gist Name/ID must be provided') if 'content' in args: self.content = args['content'] else: raise Exception('Gist content can\'t be empty') if (self.gist_name == ''): self.gist_name = self.getgist(id=self.gist_id) data = {"description": self.description, "files": { self.gist_name: { "...
data=json.dumps(data), ) if (r.status_code == 200): r_text = json.loads(r.text) response = { 'updated_content': self.content, 'created_at': r.json()['created_at'], 'comments':r.json()['comments'] } return response raise Exception('No such gist found')
def delete(self, **args): ''' Delete a gist by gistname/gistID ''' if 'name' in args: self.gist_name = args['name'] self.gist_id = self.getMyID(self.gist_name) elif 'id' in args: self.gist_id = args['id'] else: raise Exception('Provide GistName to delete') url = 'gists' if self.gist_id: r = requests.delete( '%s/%s/%s'%...
def starred(self, **args): ''' List the authenticated user's starred gists ''' ids =[] r = requests.get( '%s/gists/starred'%BASE_URL, headers=self.gist.header ) if 'limit' in args: limit = args['limit'] else: limit = len(r.json()) if (r.status_code == 200): for g in range(0,limit ): ids.append('%s/%s/%s' %(GIST_URL,r.j...
def links(self,**args): ''' Return Gist URL-Link, Clone-Link and Script-Link to embed ''' if 'name' in args: self.gist_name = args['name'] self.gist_id = self.getMyID(self.gist_name) elif 'id' in args: self.gist_id = args['id'] else: raise Exception('Gist Name/ID must be provided') if self.gist_id: r = requests.get( '%...
%(GIST_URL,self.gist.username,r.json()['id']) } return content raise Exception('No such gist found')
def load_forecasts(self): """ Load neighborhood probability forecasts. """ run_date_str = self.run_date.strftime("%Y%m%d") forecast_file = self.forecast_path + "{0}/{1}_{2}_{3}_consensus_{0}.nc".format(run_date_str, self.ensemble_name, self.model_name, self.forecast_variable) print("Forecast file: " + forecast_file) fo...
self.forecast_variable, size_threshold, smoothing_radius)) if hour_var in forecast_data.variables.keys(): self.hourly_forecasts[hour_var] = forecast_data.variables[hour_var][:] if period_var in forecast_data.variables.keys(): self.period_forecasts[period_var] = forecast_data.variables[period_var][:] forecast_data.close...
def load_obs(self, mask_threshold=0.5): """ Loads observations and masking grid (if needed). Args: mask_threshold: Values greater than the threshold are kept, others are masked. """ print("Loading obs ", self.run_date, self.model_name, self.forecast_variable) start_date = self.run_date + timedelta(hours=self.start_hour...
= MRMSGrid(start_date, end_date, self.mask_variable, self.mrms_path) mask_grid.load_data() self.raw_obs[self.mask_variable] = np.where(mask_grid.data >= mask_threshold, 1, 0) self.period_obs[self.mask_variable] = self.raw_obs[self.mask_variable].max(axis=0)
def load_coordinates(self): """ Loads lat-lon coordinates from a netCDF file. """ coord_file = Dataset(self.coordinate_file) if "lon" in coord_file.variables.keys(): self.coordinates["lon"] = coord_file.variables["lon"][:] self.coordinates["lat"] = coord_file.variables["lat"][:] else: self.coordinates["lon"] = coord_fi...
def evaluate_hourly_forecasts(self): """ Calculates ROC curves and Reliability scores for each forecast hour. Returns: A pandas DataFrame containing forecast metadata as well as DistributedROC and Reliability objects. """ score_columns = ["Run_Date", "Forecast_Hour", "Ensemble Name", "Model_Name", "Forecast_Variable", ...
print("Eval hourly forecast {0:02d} {1} {2} {3} {4:d} {5:d}".format(hour, self.model_name, self.forecast_variable, self.run_date, neighbor_radius, size_threshold)) hour_obs = fftconvolve(self.raw_obs[self.mrms_variable][h] >= self.obs_thresholds[s], n_filter, mode="same") hour_obs[hour_obs > 1] = 1 hour_obs[hour_obs < ...
hour_obs) rel = DistributedReliability(thresholds=self.probability_levels, obs_threshold=0.5) rel.update(hour_forecast, hour_obs) row = [self.run_date, hour, self.ensemble_name, self.model_name, self.forecast_variable, neighbor_radius, smoothing_radius, size_threshold, roc, rel] all_scores.loc[hour_var + "_{0:d}".forma...
def evaluate_period_forecasts(self): """ Evaluates ROC and Reliability scores for forecasts over the full period from start hour to end hour Returns: A pandas DataFrame with full-period metadata and verification statistics """ score_columns = ["Run_Date", "Ensemble Name", "Model_Name", "Forecast_Variable", "Neighbor_Ra...
& (self.coordinates["lat"] <= self.lat_bounds[1]) & (self.period_obs[self.mask_variable] > 0)) else: coord_mask = None for neighbor_radius in self.neighbor_radii: n_filter = disk(neighbor_radius) for s, size_threshold in enumerate(self.size_thresholds): period_obs = fftconvolve(self.period_obs[self.mrms_variable] >= se...
in self.smoothing_radii: print("Eval period forecast {0} {1} {2} {3} {4} {5}".format(self.model_name, self.forecast_variable, self.run_date, neighbor_radius, size_threshold, smoothing_radius)) period_var = "neighbor_prob_{0:d}-hour_r_{1:d}_s_{2:d}_{3}_{4:0.2f}".format(self.end_hour - self.start_hour + 1, neighbor_radiu...
period_obs) row = [self.run_date, self.ensemble_name, self.model_name, self.forecast_variable, neighbor_radius, smoothing_radius, size_threshold, roc, rel] all_scores.loc[period_var] = row return all_scores
def bootstrap_main(args): """ Main function explicitly called from the C++ code. Return the main application object. """ version_info = sys.version_info if version_info.major != 3 or version_info.minor < 6: return None, "python36" main_fn = load_module_as_package("nionui_app.nionswift") if main_fn: return main_fn(["nio...
def _migrate_library(workspace_dir: pathlib.Path, do_logging: bool=True) -> pathlib.Path: """ Migrate library to latest version. """ library_path_11 = workspace_dir / "Nion Swift Workspace.nslib" library_path_12 = workspace_dir / "Nion Swift Library 12.nslib" library_path_13 = workspace_dir / "Nion Swift Library 13.nsl...
break return library_path_latest
def status(self): """Nome amigável do campo ``ESTADO_OPERACAO``, conforme a "Tabela de Informações do Status do SAT". """ for valor, rotulo in ESTADOS_OPERACAO: if self.ESTADO_OPERACAO == valor: return rotulo return u'(desconhecido: {})'.format(self.ESTADO_OPERACAO)
def analisar(retorno): """Constrói uma :class:`RespostaConsultarStatusOperacional` a partir do retorno informado. :param unicode retorno: Retorno da função ``ConsultarStatusOperacional``. """ resposta = analisar_retorno(forcar_unicode(retorno), funcao='ConsultarStatusOperacional', classe_resposta=RespostaConsultarStatu...
('DH_ULTIMA', as_datetime), ('CERT_EMISSAO', as_date), ('CERT_VENCIMENTO', as_date), ('ESTADO_OPERACAO', int), ), campos_alternativos=[ # se falhar resultarão apenas os 5 campos padrão RespostaSAT.CAMPOS, ] ) if resposta.EEEEE not in ('10000',): raise ExcecaoRespostaSAT(resposta) return resposta
def merge_input_csv_forecast_json(input_csv_file, forecast_json_path, condition_models, dist_models): """ Reads forecasts from json files and merges them with the input data from the step csv files. Args: input_csv_file: Name of the input data csv file being processed forecast_json_path: Path to the forecast json files...
distribution Returns: """ try: run_date = input_csv_file[:-4].split("_")[-1] print(run_date) ens_member = "_".join(input_csv_file.split("/")[-1][:-4].split("_")[3:-1]) ens_name = input_csv_file.split("/")[-1].split("_")[2] input_data = pd.read_csv(input_csv_file, index_col="Step_ID") full_json_path = forecast_json_path...
model_pred_cols.append(dist_model.replace(" ", "-") + "_" + param) pred_data = pd.DataFrame(index=input_data.index, columns=model_pred_cols, dtype=float) for track_id in track_ids: track_id_num = track_id.split("_")[-1] json_filename = full_json_path + "{0}_{1}_{2}_model_track_{3}.json".format(ens_name, run_date, ens_m...
+ p for p in gamma_params]] = step["properties"]["dist_" + dist_model] out_data = input_data.merge(pred_data, left_index=True, right_index=True) return out_data, ens_name, ens_member except Exception as e: print(traceback.format_exc()) raise e
def mark_data_dirty(self): """ Called from item to indicate its data or metadata has changed.""" self.__cache.set_cached_value_dirty(self.__display_item, self.__cache_property_name) self.__initialize_cache() self.__cached_value_dirty = True
def __initialize_cache(self): """Initialize the cache values (cache values are used for optimization).""" if self.__cached_value_dirty is None: self.__cached_value_dirty = self.__cache.is_cached_value_dirty(self.__display_item, self.__cache_property_name) self.__cached_value = self.__cache.get_cached_value(self.__displ...
def recompute_if_necessary(self, ui): """Recompute the data on a thread, if necessary. If the data has recently been computed, this call will be rescheduled for the future. If the data is currently being computed, it do nothing.""" self.__initialize_cache() if self.__cached_value_dirty: with self.__is_recomputing_lock:...
# this has the side effect of limiting the number of threads that # are sleeping. def recompute(): try: if self.__recompute_thread_cancel.wait(0.01): # helps tests run faster return minimum_time = 0.5 current_time = time.time() if current_time < self.__cached_value_time + minimum_time: if self.__recompute_thread_cancel...
def recompute_data(self, ui): """Compute the data associated with this processor. This method is thread safe and may take a long time to return. It should not be called from the UI thread. Upon return, the results will be calculated with the latest data available and the cache will not be marked dirty. """ self.__initi...
as e: import traceback traceback.print_exc() traceback.print_stack() raise self.__cache.set_cached_value(self.__display_item, self.__cache_property_name, calculated_data) self.__cached_value = calculated_data self.__cached_value_dirty = False self.__cached_value_time = time.time() else: calculated_data = None if calcul...
everything from the cache self.__cache.remove_cached_value(self.__display_item, self.__cache_property_name) self.__cached_value = None self.__cached_value_dirty = None self.__cached_value_time = 0 self.__recompute_lock.release() if callable(self.on_thumbnail_updated): self.on_thumbnail_updated() self.__recompute_lock.a...
def thumbnail_source_for_display_item(self, ui, display_item: DisplayItem.DisplayItem) -> ThumbnailSource: """Returned ThumbnailSource must be closed.""" with self.__lock: thumbnail_source = self.__thumbnail_sources.get(display_item) if not thumbnail_source: thumbnail_source = ThumbnailSource(ui, display_item) self.__t...
def load_plug_ins(app, root_dir): """Load plug-ins.""" global extensions ui = app.ui # a list of directories in which sub-directories PlugIns will be searched. subdirectories = [] # the default location is where the directory main packages are located. if root_dir: subdirectories.append(root_dir) # also search the defa...
will be application specific. data_location = ui.get_data_location() if data_location is not None: subdirectories.append(data_location) # create directories here if they don't exist plugins_dir = os.path.abspath(os.path.join(data_location, "PlugIns")) if not os.path.exists(plugins_dir): logging.info("Creating plug-ins ...
None: subdirectories.append(os.path.join(document_location, "Nion", "Swift")) # do not create them in documents if they don't exist. this location is optional. # build a list of directories that will be loaded as plug-ins. PlugInDir = collections.namedtuple("PlugInDir", ["directory", "relative_path"]) plugin_dirs = lis...
subdirectory in subdirectories: plugins_dir = os.path.abspath(os.path.join(subdirectory, "PlugIns")) if os.path.exists(plugins_dir) and not plugins_dir in seen_plugin_dirs: logging.info("Loading plug-ins from %s", plugins_dir) # add the PlugIns directory to the system import path. sys.path.append(plugins_dir) # now bui...
search it twice. seen_plugin_dirs.append(plugins_dir) else: logging.info("NOT Loading plug-ins from %s (missing)", plugins_dir) version_map = dict() module_exists_map = dict() plugin_adapters = list() import nionswift_plugin for module_info in pkgutil.iter_modules(nionswift_plugin.__path__): plugin_adapters.append(Modu...
True if not "name" in manifest: logging.info("Invalid manifest (missing 'name'): %s", manifest_path) manifest_valid = False if not "identifier" in manifest: logging.info("Invalid manifest (missing 'identifier'): %s", manifest_path) manifest_valid = False if "identifier" in manifest and not re.match("[_\-a-zA-Z][_\-a-zA...
in manifest and not isinstance(manifest["requires"], list): logging.info("Invalid manifest ('requires' not a list): %s", manifest_path) manifest_valid = False if not manifest_valid: continue for module in manifest.get("modules", list()): if module in module_exists_map: module_exists = module_exists_map.get(module) else...
module, manifest_path) manifest_valid = False break for requirement in manifest.get("requires", list()): # TODO: see https://packaging.pypa.io/en/latest/ requirement_components = requirement.split() if len(requirement_components) != 3 or requirement_components[1] != "~=": logging.info("Invalid manifest (requirement '%s...
(" + plugin_adapter.module_path + ").") logging.info("Cannot satisfy requirement (%s): %s", requirement, manifest_path) manifest_valid = False break else: # requirements not loaded yet; add back to plugin_adapters, but don't mark progress since nothing was loaded. logging.info("Plug-in '" + plugin_adapter.module_name +...
if any # repeat loop of plug-ins until no plug-ins left in the list # if all dependencies satisfied for a plug-in, load it # otherwise defer until next round # stop if no plug-ins loaded in the round # count on the user to have correct dependencies module = plugin_adapter.load() if module: __modules.append(module) prog...
plugin_adapter.module_name + "' NOT loaded (requirements) (" + plugin_adapter.module_path + ").") notify_modules("run")
def getMyID(self,gist_name): ''' Getting gistID of a gist in order to make the workflow easy and uninterrupted. ''' r = requests.get( '%s'%BASE_URL+'/users/%s/gists' % self.user, headers=self.gist.header ) if (r.status_code == 200): r_text = json.loads(r.text) limit = len(r.json()) for g,no in zip(r_text, range(0,limit...
def close(self): """Close the document controller. This method must be called to shut down the document controller. There are several paths by which it can be called, though. * User quits application via menu item. The menu item will call back to Application.exit which will close each document controller by calling thi...
will call aboutToClose in the document windows * User closes document window via menu item. * User closes document window via close box. The main concept of closing is that it is always triggered by the document window closing. This can be initiated from within Python by calling request_close on the document window. Wh...
user clicking a close box, it will invoke the about_to_close method on the document window. At this point, the window would still be open, so the about_to_close message can be used to tell the document controller to save anything it needs to save and prepare for closing. """ assert self.__closed == False self.__closed ...
# dialogs for weak_dialog in self.__dialogs: dialog = weak_dialog() if dialog: try: dialog.request_close() except Exception as e: pass # menus self._file_menu = None self._edit_menu = None self._processing_menu = None self._view_menu = None self._window_menu = None self._help_menu = None self._library_menu = None self....
None self._display_type_menu = None if self.__workspace_controller: self.__workspace_controller.close() self.__workspace_controller = None self.__call_soon_event_listener.close() self.__call_soon_event_listener = None self.__filtered_display_items_model.close() self.__filtered_display_items_model = None self.filter_con...
def add_periodic(self, interval: float, listener_fn): """Add a listener function and return listener token. Token can be closed or deleted to unlisten.""" class PeriodicListener: def __init__(self, interval: float, listener_fn): self.interval = interval self.__listener_fn = listener_fn # the call function is very perfo...
void(*args, **kwargs): pass self.call = void self.next_scheduled_time = time.time() + interval def close(self): self.__listener_fn = None def void(*args, **kwargs): pass self.call = void listener = PeriodicListener(interval, listener_fn) def remove_listener(weak_listener): with self.__weak_periodic_listeners_mutex: sel...
def __update_display_items_model(self, display_items_model: ListModel.FilteredListModel, data_group: typing.Optional[DataGroup.DataGroup], filter_id: typing.Optional[str]) -> None: """Update the data item model with a new container, filter, and sorting. This is called when the data item model is created or when the use...
= None display_items_model.filter_id = None elif filter_id == "latest-session": display_items_model.container = self.document_model display_items_model.filter = ListModel.EqFilter("session_id", self.document_model.session_id) display_items_model.sort_key = DataItem.sort_by_date_key display_items_model.sort_reverse = Tr...
DataItem.sort_by_date_key display_items_model.sort_reverse = True display_items_model.filter_id = filter_id else: # "all" display_items_model.container = self.document_model display_items_model.filter = ListModel.EqFilter("category", "persistent") display_items_model.sort_key = DataItem.sort_by_date_key display_items_m...
def focused_data_item(self) -> typing.Optional[DataItem.DataItem]: """Return the data item with keyboard focus.""" return self.__focused_display_item.data_item if self.__focused_display_item else None
def selected_display_item(self) -> typing.Optional[DisplayItem.DisplayItem]: """Return the selected display item. The selected display is the display ite that has keyboard focus in the data panel or a display panel. """ # first check for the [focused] data browser display_item = self.focused_display_item if not display...
def _get_two_data_sources(self): """Get two sensible data sources, which may be the same.""" selected_display_items = self.selected_display_items if len(selected_display_items) < 2: selected_display_items = list() display_item = self.selected_display_item if display_item: selected_display_items.append(display_item) if ...
and isinstance(graphic1, Graphics.IntervalGraphic) and isinstance(graphic2, Graphics.IntervalGraphic): crop_graphic1 = graphic1 crop_graphic2 = graphic2 elif data_item.is_datum_2d and isinstance(graphic1, Graphics.RectangleTypeGraphic) and isinstance(graphic2, Graphics.RectangleTypeGraphic): crop_graphic1 = graphic1 cr...
selected_display_items[1] crop_graphic2 = self.__get_crop_graphic(display_item2) return (display_item1, crop_graphic1), (display_item2, crop_graphic2) return None
def calculate_origin_and_size(canvas_size, data_shape, image_canvas_mode, image_zoom, image_position) -> typing.Tuple[typing.Any, typing.Any]: """Calculate origin and size for canvas size, data shape, and image display parameters.""" if data_shape is None: return None, None if image_canvas_mode == "fill": data_shape = ...
/ data_shape[1], canvas_size[1]) image_canvas_origin = (canvas_size[0] * 0.5 - image_canvas_size[0] * 0.5, canvas_size[1] * 0.5 - image_canvas_size[1] * 0.5) elif image_canvas_mode == "fit": image_canvas_size = canvas_size image_canvas_origin = (0, 0) elif image_canvas_mode == "1:1": image_canvas_size = data_shape imag...
0.5) image_canvas_origin = (canvas_size[0] * 0.5 - image_canvas_size[0] * 0.5, canvas_size[1] * 0.5 - image_canvas_size[1] * 0.5) else: image_canvas_size = (canvas_size[0] * image_zoom, canvas_size[1] * image_zoom) canvas_rect = Geometry.fit_to_size(((0, 0), image_canvas_size), data_shape) image_canvas_origin_y = (canv...
def read_library(persistent_storage_system, ignore_older_files) -> typing.Dict: """Read data items from the data reference handler and return as a list. Data items will have persistent_object_context set upon return, but caller will need to call finish_reading on each of the data items. """ data_item_uuids = set() util...
utilized_deletions=utilized_deletions, ignore_older_files=ignore_older_files) # next, for each auto migration, create a temporary storage system and read items from that storage system # using auto_migrate_storage_system. the data items returned will have been copied to the current storage # system (persistent object c...
len(reader_info_list) == len(data_item_uuids) library_storage_properties = persistent_storage_system.library_storage_properties for reader_info in reader_info_list: properties = reader_info.properties properties = Utility.clean_dict(copy.deepcopy(properties) if properties else dict()) version = properties.get("version"...
# and would be migrated during reading unless they explicitly are prevented from doing so (via data_item_deletions). # utilized deletions are the ones that were attempted; if nothing was attempted, then no reason to track it anymore # since there is nothing to migrate in the future. library_storage_properties["data_ite...
in connections_list}) computations_list = library_storage_properties.get("computations", list()) assert len(computations_list) == len({computation.get("uuid") for computation in computations_list}) # migrations if library_storage_properties.get("version", 0) < 2: for data_group_properties in library_storage_properties....
display_to_display_item_map = dict() display_to_display_data_channel_map = dict() for display_item_properties in library_storage_properties.get("display_items", list()): display_to_display_item_map[display_item_properties["display"]["uuid"]] = display_item_properties["uuid"] display_to_display_data_channel_map[display_...
d["display_item_uuid"] = display_item_uuid_str replace1(workspace_properties["layout"]) for connection_dict in library_storage_properties.get("connections", list()): source_uuid_str = connection_dict["source_uuid"] if connection_dict["type"] == "interval-list-connection": connection_dict["source_uuid"] = display_to_dis...
specifier_dict["type"] = "data_item" if specifier_dict.get("type") == "region": specifier_dict["type"] = "graphic" for computation_dict in library_storage_properties.get("computations", list()): for variable_dict in computation_dict.get("variables", list()): if "specifier" in variable_dict: specifier_dict = variable_di...
uuid] such as connections or computations or data items assert library_storage_properties["version"] == DocumentModel.DocumentModel.library_version persistent_storage_system.rewrite_properties(library_storage_properties) properties = copy.deepcopy(library_storage_properties) for reader_info in reader_info_list: data_it...
def auto_migrate_storage_system(*, persistent_storage_system=None, new_persistent_storage_system=None, data_item_uuids=None, deletions: typing.List[uuid.UUID] = None, utilized_deletions: typing.Set[uuid.UUID] = None, ignore_older_files: bool = True): """Migrate items from the storage system to the object context. Files...
have persistent_object_context set upon return, but caller will need to call finish_reading on each of the data items. """ storage_handlers = persistent_storage_system.find_data_items() ReaderInfo = collections.namedtuple("ReaderInfo", ["properties", "changed_ref", "large_format", "storage_handler", "identifier"]) read...
traceback.print_stack() library_storage_properties = persistent_storage_system.library_storage_properties for deletion in copy.deepcopy(library_storage_properties.get("data_item_deletions", list())): if not deletion in deletions: deletions.append(deletion) preliminary_library_updates = dict() library_updates = dict() i...