Dataset Viewer (First 5GB)
Auto-converted to Parquet Duplicate
query
stringlengths
1
46.9k
pos
stringlengths
75
104k
neg
listlengths
12
12
scores
listlengths
12
12
Estimate discontinuity in basis of low resolution image segmentation. :return: discontinuity in low resolution
def __msgc_step3_discontinuity_localization(self): """ Estimate discontinuity in basis of low resolution image segmentation. :return: discontinuity in low resolution """ import scipy start = self._start_time seg = 1 - self.segmentation.astype(np.int8) self.stats["low level object voxels"] = np.sum(seg) self.stats["low level image voxels"] = np.prod(seg.shape) # in seg is now stored low resolution segmentation # back to normal parameters # step 2: discontinuity localization # self.segparams = sparams_hi seg_border = scipy.ndimage.filters.laplace(seg, mode="constant") logger.debug("seg_border: %s", scipy.stats.describe(seg_border, axis=None)) # logger.debug(str(np.max(seg_border))) # logger.debug(str(np.min(seg_border))) seg_border[seg_border != 0] = 1 logger.debug("seg_border: %s", scipy.stats.describe(seg_border, axis=None)) # scipy.ndimage.morphology.distance_transform_edt boundary_dilatation_distance = self.segparams["boundary_dilatation_distance"] seg = scipy.ndimage.morphology.binary_dilation( seg_border, # seg, np.ones( [ (boundary_dilatation_distance * 2) + 1, (boundary_dilatation_distance * 2) + 1, (boundary_dilatation_distance * 2) + 1, ] ), ) if self.keep_temp_properties: self.temp_msgc_lowres_discontinuity = seg else: self.temp_msgc_lowres_discontinuity = None if self.debug_images: import sed3 pd = sed3.sed3(seg_border) # ), contour=seg) pd.show() pd = sed3.sed3(seg) # ), contour=seg) pd.show() # segzoom = scipy.ndimage.interpolation.zoom(seg.astype('float'), zoom, # order=0).astype('int8') self.stats["t3"] = time.time() - start return seg
[ "def branchScale(self):\n \"\"\"See docs for `Model` abstract base class.\"\"\"\n bs = -(self.prx * scipy.diagonal(self.Prxy, axis1=1, axis2=2)\n ).sum() * self.mu / float(self.nsites)\n assert bs > 0\n return bs", "def branchScale(self):\n \"\"\"See docs for `Model` abstract base class.\"\"\"\n bs = -(self.Phi_x * scipy.diagonal(self.Pxy[0])).sum() * self.mu\n assert bs > 0\n return bs", "def __msgc_step12_low_resolution_segmentation(self):\n \"\"\"\n Get the segmentation and the\n :return:\n \"\"\"\n import scipy\n\n start = self._start_time\n # ===== low resolution data processing\n # default parameters\n # TODO segparams_lo and segparams_hi je tam asi zbytecně\n sparams_lo = {\n \"boundary_dilatation_distance\": 2,\n \"block_size\": 6,\n \"use_boundary_penalties\": True,\n \"boundary_penalties_weight\": 1,\n \"tile_zoom_constant\": 1,\n }\n\n sparams_lo.update(self.segparams)\n sparams_hi = copy.copy(sparams_lo)\n # sparams_lo['boundary_penalties_weight'] = (\n # sparams_lo['boundary_penalties_weight'] *\n # sparams_lo['block_size'])\n self.segparams = sparams_lo\n\n self.stats[\"t1\"] = time.time() - start\n # step 1: low res GC\n hiseeds = self.seeds\n # ms_zoom = 4 # 0.125 #self.segparams['scale']\n # ms_zoom = self.segparams['block_size']\n # loseeds = pyed.getSeeds()\n # logger.debug(\"msc \" + str(np.unique(hiseeds)))\n loseeds = seed_zoom(hiseeds, self.segparams[\"block_size\"])\n\n hard_constraints = True\n\n self.seeds = loseeds\n\n modelparams_hi = self.modelparams.copy()\n # feature vector will be computed from selected voxels\n self.modelparams[\"use_extra_features_for_training\"] = True\n\n # TODO what with voxels? It is used from here\n # hiseeds and hiimage is used to create intensity model\n self.voxels1 = self.img[hiseeds == 1].reshape(-1, 1)\n self.voxels2 = self.img[hiseeds == 2].reshape(-1, 1)\n # this is how to compute with loseeds resolution but in wrong way\n # self.voxels1 = self.img[self.seeds == 1]\n # self.voxels2 = self.img[self.seeds == 2]\n\n # self.voxels1 = pyed.getSeedsVal(1)\n # self.voxels2 = pyed.getSeedsVal(2)\n\n img_orig = self.img\n\n # TODO this should be done with resize_to_shape_whith_zoom\n zoom = np.asarray(loseeds.shape).astype(np.float) / img_orig.shape\n self.img = scipy.ndimage.interpolation.zoom(img_orig, zoom, order=0)\n voxelsize_orig = self.voxelsize\n logger.debug(\"zoom %s\", zoom)\n logger.debug(\"vs %s\", self.voxelsize)\n self.voxelsize = self.voxelsize * zoom\n\n # self.img = resize_to_shape_with_zoom(img_orig, loseeds.shape, 1.0 / ms_zoom, order=0)\n\n # this step set the self.segmentation\n self.__single_scale_gc_run()\n # logger.debug(\n # 'segmentation - max: %d min: %d' % (\n # np.max(self.segmentation),\n # np.min(self.segmentation)\n # )\n # )\n logger.debug(\n \"segmentation: %s\", scipy.stats.describe(self.segmentation, axis=None)\n )\n\n self.modelparams = modelparams_hi\n self.voxelsize = voxelsize_orig\n self.img = img_orig\n self.seeds = hiseeds\n self.stats[\"t2\"] = time.time() - start\n return hard_constraints", "def __multiscale_gc_lo2hi_run(self): # , pyed):\n \"\"\"\n Run Graph-Cut segmentation with refinement of low resolution multiscale graph.\n In first step is performed normal GC on low resolution data\n Second step construct finer grid on edges of segmentation from first\n step.\n There is no option for use without `use_boundary_penalties`\n \"\"\"\n # from PyQt4.QtCore import pyqtRemoveInputHook\n # pyqtRemoveInputHook()\n self._msgc_lo2hi_resize_init()\n self.__msgc_step0_init()\n\n hard_constraints = self.__msgc_step12_low_resolution_segmentation()\n # ===== high resolution data processing\n seg = self.__msgc_step3_discontinuity_localization()\n\n self.stats[\"t3.1\"] = (time.time() - self._start_time)\n graph = Graph(\n seg,\n voxelsize=self.voxelsize,\n nsplit=self.segparams[\"block_size\"],\n edge_weight_table=self._msgc_npenalty_table,\n compute_low_nodes_index=True,\n )\n\n # graph.run() = graph.generate_base_grid() + graph.split_voxels()\n # graph.run()\n graph.generate_base_grid()\n self.stats[\"t3.2\"] = (time.time() - self._start_time)\n graph.split_voxels()\n\n self.stats[\"t3.3\"] = (time.time() - self._start_time)\n\n self.stats.update(graph.stats)\n self.stats[\"t4\"] = (time.time() - self._start_time)\n mul_mask, mul_val = self.__msgc_tlinks_area_weight_from_low_segmentation(seg)\n area_weight = 1\n unariesalt = self.__create_tlinks(\n self.img,\n self.voxelsize,\n self.seeds,\n area_weight=area_weight,\n hard_constraints=hard_constraints,\n mul_mask=None,\n mul_val=None,\n )\n # N-links prepared\n self.stats[\"t5\"] = (time.time() - self._start_time)\n un, ind = np.unique(graph.msinds, return_index=True)\n self.stats[\"t6\"] = (time.time() - self._start_time)\n\n self.stats[\"t7\"] = (time.time() - self._start_time)\n unariesalt2_lo2hi = np.hstack(\n [unariesalt[ind, 0, 0].reshape(-1, 1), unariesalt[ind, 0, 1].reshape(-1, 1)]\n )\n nlinks_lo2hi = np.hstack([graph.edges, graph.edges_weights.reshape(-1, 1)])\n if self.debug_images:\n import sed3\n\n ed = sed3.sed3(unariesalt[:, :, 0].reshape(self.img.shape))\n ed.show()\n import sed3\n\n ed = sed3.sed3(unariesalt[:, :, 1].reshape(self.img.shape))\n ed.show()\n # ed = sed3.sed3(seg)\n # ed.show()\n # import sed3\n # ed = sed3.sed3(graph.data)\n # ed.show()\n # import sed3\n # ed = sed3.sed3(graph.msinds)\n # ed.show()\n\n # nlinks, unariesalt2, msinds = self.__msgc_step45678_construct_graph(area_weight, hard_constraints, seg)\n # self.__msgc_step9_finish_perform_gc_and_reshape(nlinks, unariesalt2, msinds)\n self.__msgc_step9_finish_perform_gc_and_reshape(\n nlinks_lo2hi, unariesalt2_lo2hi, graph.msinds\n )\n self._msgc_lo2hi_resize_clean_finish()", "def __multiscale_gc_hi2lo_run(self): # , pyed):\n \"\"\"\n Run Graph-Cut segmentation with simplifiyng of high resolution multiscale graph.\n In first step is performed normal GC on low resolution data\n Second step construct finer grid on edges of segmentation from first\n step.\n There is no option for use without `use_boundary_penalties`\n \"\"\"\n # from PyQt4.QtCore import pyqtRemoveInputHook\n # pyqtRemoveInputHook()\n\n self.__msgc_step0_init()\n hard_constraints = self.__msgc_step12_low_resolution_segmentation()\n # ===== high resolution data processing\n seg = self.__msgc_step3_discontinuity_localization()\n nlinks, unariesalt2, msinds = self.__msgc_step45678_hi2lo_construct_graph(\n hard_constraints, seg\n )\n self.__msgc_step9_finish_perform_gc_and_reshape(nlinks, unariesalt2, msinds)", "def estimateBackgroundLevel(img, image_is_artefact_free=False, \r\n min_rel_size=0.05, max_abs_size=11):\r\n '''\r\n estimate background level through finding the most homogeneous area\r\n and take its average\r\n \r\n min_size - relative size of the examined area\r\n '''\r\n\r\n s0,s1 = img.shape[:2]\r\n s = min(max_abs_size, int(max(s0,s1)*min_rel_size))\r\n arr = np.zeros(shape=(s0-2*s, s1-2*s), dtype=img.dtype)\r\n \r\n #fill arr:\r\n _spatialStd(img, arr, s)\r\n #most homogeneous area:\r\n i,j = np.unravel_index(arr.argmin(), arr.shape)\r\n sub = img[int(i+0.5*s):int(i+s*1.5), \r\n int(j+s*0.5):int(j+s*1.5)]\r\n\r\n return np.median(sub)", "def _convert_slice_incement_inconsistencies(dicom_input):\n \"\"\"\n If there is slice increment inconsistency detected, for the moment CT images, then split the volumes into subvolumes based on the slice increment and process each volume separately using a space constructed based on the highest resolution increment\n \"\"\"\n\n # Estimate the \"first\" slice increment based on the 2 first slices\n increment = numpy.array(dicom_input[0].ImagePositionPatient) - numpy.array(dicom_input[1].ImagePositionPatient)\n\n # Create as many volumes as many changes in slice increment. NB Increments might be repeated in different volumes\n max_slice_increment = 0\n slice_incement_groups = []\n current_group = [dicom_input[0], dicom_input[1]]\n previous_image_position = numpy.array(dicom_input[1].ImagePositionPatient)\n for dicom in dicom_input[2:]:\n current_image_position = numpy.array(dicom.ImagePositionPatient)\n current_increment = previous_image_position - current_image_position\n max_slice_increment = max(max_slice_increment, numpy.linalg.norm(current_increment))\n if numpy.allclose(increment, current_increment, rtol=0.05, atol=0.1):\n current_group.append(dicom)\n if not numpy.allclose(increment, current_increment, rtol=0.05, atol=0.1):\n slice_incement_groups.append(current_group)\n current_group = [current_group[-1], dicom]\n increment = current_increment\n previous_image_position = current_image_position\n slice_incement_groups.append(current_group)\n\n # Create nibabel objects for each volume based on the corresponding headers\n slice_incement_niftis = []\n for dicom_slices in slice_incement_groups:\n data = common.get_volume_pixeldata(dicom_slices)\n affine, _ = common.create_affine(dicom_slices)\n slice_incement_niftis.append(nibabel.Nifti1Image(data, affine))\n\n nifti_volume = resample.resample_nifti_images(slice_incement_niftis)\n\n return nifti_volume, max_slice_increment", "def segment(self):\n \"\"\"An non-overlap version Compror\"\"\"\n\n if not self.seg:\n j = 0\n else:\n j = self.seg[-1][1]\n last_len = self.seg[-1][0]\n if last_len + j > self.n_states:\n return\n\n i = j\n while j < self.n_states - 1:\n while not (not (i < self.n_states - 1) or not (self.lrs[i + 1] >= i - j + 1)):\n i += 1\n if i == j:\n i += 1\n self.seg.append((0, i))\n else:\n if (self.sfx[i] + self.lrs[i]) <= i:\n self.seg.append((i - j, self.sfx[i] - i + j + 1))\n\n else:\n _i = j + i - self.sfx[i]\n self.seg.append((_i - j, self.sfx[i] - i + j + 1))\n _j = _i\n while not (not (_i < i) or not (self.lrs[_i + 1] - self.lrs[_j] >= _i - _j + 1)):\n _i += 1\n if _i == _j:\n _i += 1\n self.seg.append((0, _i))\n else:\n self.seg.append((_i - _j, self.sfx[_i] - _i + _j + 1))\n j = i\n return self.seg", "def get_step(self, tol):\n '''Return step at which bound falls below tolerance. '''\n return 2 * numpy.log(tol/2.)/numpy.log(self.base)", "def get_interpolated_gap(self, tol=0.001, abs_tol=False, spin=None):\n \"\"\"\n Expects a DOS object and finds the gap\n\n Args:\n tol: tolerance in occupations for determining the gap\n abs_tol: Set to True for an absolute tolerance and False for a\n relative one.\n spin: Possible values are None - finds the gap in the summed\n densities, Up - finds the gap in the up spin channel,\n Down - finds the gap in the down spin channel.\n\n Returns:\n (gap, cbm, vbm):\n Tuple of floats in eV corresponding to the gap, cbm and vbm.\n \"\"\"\n\n tdos = self.y if len(self.ydim) == 1 else np.sum(self.y, axis=1)\n if not abs_tol:\n tol = tol * tdos.sum() / tdos.shape[0]\n energies = self.x\n below_fermi = [i for i in range(len(energies))\n if energies[i] < self.efermi and tdos[i] > tol]\n above_fermi = [i for i in range(len(energies))\n if energies[i] > self.efermi and tdos[i] > tol]\n vbm_start = max(below_fermi)\n cbm_start = min(above_fermi)\n if vbm_start == cbm_start:\n return 0.0, self.efermi, self.efermi\n else:\n # Interpolate between adjacent values\n terminal_dens = tdos[vbm_start:vbm_start + 2][::-1]\n terminal_energies = energies[vbm_start:vbm_start + 2][::-1]\n start = get_linear_interpolated_value(terminal_dens,\n terminal_energies, tol)\n terminal_dens = tdos[cbm_start - 1:cbm_start + 1]\n terminal_energies = energies[cbm_start - 1:cbm_start + 1]\n end = get_linear_interpolated_value(terminal_dens,\n terminal_energies, tol)\n return end - start, end, start", "def _get_bandgap_doscar(filename):\n \"\"\"Get the bandgap from the DOSCAR file\"\"\"\n with open(filename) as fp:\n for i in range(6):\n l = fp.readline()\n efermi = float(l.split()[3])\n step1 = fp.readline().split()[0]\n step2 = fp.readline().split()[0]\n step_size = float(step2)-float(step1)\n not_found = True\n while not_found:\n l = fp.readline().split()\n e = float(l.pop(0))\n dens = 0.0\n for i in range(int(len(l)/2)):\n dens += float(l[i])\n if e < efermi and dens > 1e-3:\n bot = e\n elif e > efermi and dens > 1e-3:\n top = e\n not_found = False\n if top - bot < step_size*2:\n bandgap = 0.0\n else:\n bandgap = float(top - bot)\n\n return bandgap", "def _cutoff(self, coeffs, vscale):\n \"\"\"\n Compute cutoff index after which the coefficients are deemed negligible.\n \"\"\"\n bnd = self._threshold(vscale)\n inds = np.nonzero(abs(coeffs) >= bnd)\n if len(inds[0]):\n N = inds[0][-1]\n else:\n N = 0\n return N+1" ]
[ 0.6861903071403503, 0.6760287284851074, 0.6727304458618164, 0.6622427105903625, 0.6478081941604614, 0.6416714191436768, 0.6381795406341553, 0.6336018443107605, 0.633543848991394, 0.6316496729850769, 0.6313363313674927, 0.6291797757148743 ]
Run Graph-Cut segmentation with refinement of low resolution multiscale graph. In first step is performed normal GC on low resolution data Second step construct finer grid on edges of segmentation from first step. There is no option for use without `use_boundary_penalties`
def __multiscale_gc_lo2hi_run(self): # , pyed): """ Run Graph-Cut segmentation with refinement of low resolution multiscale graph. In first step is performed normal GC on low resolution data Second step construct finer grid on edges of segmentation from first step. There is no option for use without `use_boundary_penalties` """ # from PyQt4.QtCore import pyqtRemoveInputHook # pyqtRemoveInputHook() self._msgc_lo2hi_resize_init() self.__msgc_step0_init() hard_constraints = self.__msgc_step12_low_resolution_segmentation() # ===== high resolution data processing seg = self.__msgc_step3_discontinuity_localization() self.stats["t3.1"] = (time.time() - self._start_time) graph = Graph( seg, voxelsize=self.voxelsize, nsplit=self.segparams["block_size"], edge_weight_table=self._msgc_npenalty_table, compute_low_nodes_index=True, ) # graph.run() = graph.generate_base_grid() + graph.split_voxels() # graph.run() graph.generate_base_grid() self.stats["t3.2"] = (time.time() - self._start_time) graph.split_voxels() self.stats["t3.3"] = (time.time() - self._start_time) self.stats.update(graph.stats) self.stats["t4"] = (time.time() - self._start_time) mul_mask, mul_val = self.__msgc_tlinks_area_weight_from_low_segmentation(seg) area_weight = 1 unariesalt = self.__create_tlinks( self.img, self.voxelsize, self.seeds, area_weight=area_weight, hard_constraints=hard_constraints, mul_mask=None, mul_val=None, ) # N-links prepared self.stats["t5"] = (time.time() - self._start_time) un, ind = np.unique(graph.msinds, return_index=True) self.stats["t6"] = (time.time() - self._start_time) self.stats["t7"] = (time.time() - self._start_time) unariesalt2_lo2hi = np.hstack( [unariesalt[ind, 0, 0].reshape(-1, 1), unariesalt[ind, 0, 1].reshape(-1, 1)] ) nlinks_lo2hi = np.hstack([graph.edges, graph.edges_weights.reshape(-1, 1)]) if self.debug_images: import sed3 ed = sed3.sed3(unariesalt[:, :, 0].reshape(self.img.shape)) ed.show() import sed3 ed = sed3.sed3(unariesalt[:, :, 1].reshape(self.img.shape)) ed.show() # ed = sed3.sed3(seg) # ed.show() # import sed3 # ed = sed3.sed3(graph.data) # ed.show() # import sed3 # ed = sed3.sed3(graph.msinds) # ed.show() # nlinks, unariesalt2, msinds = self.__msgc_step45678_construct_graph(area_weight, hard_constraints, seg) # self.__msgc_step9_finish_perform_gc_and_reshape(nlinks, unariesalt2, msinds) self.__msgc_step9_finish_perform_gc_and_reshape( nlinks_lo2hi, unariesalt2_lo2hi, graph.msinds ) self._msgc_lo2hi_resize_clean_finish()
[ "def __multiscale_gc_hi2lo_run(self): # , pyed):\n \"\"\"\n Run Graph-Cut segmentation with simplifiyng of high resolution multiscale graph.\n In first step is performed normal GC on low resolution data\n Second step construct finer grid on edges of segmentation from first\n step.\n There is no option for use without `use_boundary_penalties`\n \"\"\"\n # from PyQt4.QtCore import pyqtRemoveInputHook\n # pyqtRemoveInputHook()\n\n self.__msgc_step0_init()\n hard_constraints = self.__msgc_step12_low_resolution_segmentation()\n # ===== high resolution data processing\n seg = self.__msgc_step3_discontinuity_localization()\n nlinks, unariesalt2, msinds = self.__msgc_step45678_hi2lo_construct_graph(\n hard_constraints, seg\n )\n self.__msgc_step9_finish_perform_gc_and_reshape(nlinks, unariesalt2, msinds)", "def __msgc_step12_low_resolution_segmentation(self):\n \"\"\"\n Get the segmentation and the\n :return:\n \"\"\"\n import scipy\n\n start = self._start_time\n # ===== low resolution data processing\n # default parameters\n # TODO segparams_lo and segparams_hi je tam asi zbytecně\n sparams_lo = {\n \"boundary_dilatation_distance\": 2,\n \"block_size\": 6,\n \"use_boundary_penalties\": True,\n \"boundary_penalties_weight\": 1,\n \"tile_zoom_constant\": 1,\n }\n\n sparams_lo.update(self.segparams)\n sparams_hi = copy.copy(sparams_lo)\n # sparams_lo['boundary_penalties_weight'] = (\n # sparams_lo['boundary_penalties_weight'] *\n # sparams_lo['block_size'])\n self.segparams = sparams_lo\n\n self.stats[\"t1\"] = time.time() - start\n # step 1: low res GC\n hiseeds = self.seeds\n # ms_zoom = 4 # 0.125 #self.segparams['scale']\n # ms_zoom = self.segparams['block_size']\n # loseeds = pyed.getSeeds()\n # logger.debug(\"msc \" + str(np.unique(hiseeds)))\n loseeds = seed_zoom(hiseeds, self.segparams[\"block_size\"])\n\n hard_constraints = True\n\n self.seeds = loseeds\n\n modelparams_hi = self.modelparams.copy()\n # feature vector will be computed from selected voxels\n self.modelparams[\"use_extra_features_for_training\"] = True\n\n # TODO what with voxels? It is used from here\n # hiseeds and hiimage is used to create intensity model\n self.voxels1 = self.img[hiseeds == 1].reshape(-1, 1)\n self.voxels2 = self.img[hiseeds == 2].reshape(-1, 1)\n # this is how to compute with loseeds resolution but in wrong way\n # self.voxels1 = self.img[self.seeds == 1]\n # self.voxels2 = self.img[self.seeds == 2]\n\n # self.voxels1 = pyed.getSeedsVal(1)\n # self.voxels2 = pyed.getSeedsVal(2)\n\n img_orig = self.img\n\n # TODO this should be done with resize_to_shape_whith_zoom\n zoom = np.asarray(loseeds.shape).astype(np.float) / img_orig.shape\n self.img = scipy.ndimage.interpolation.zoom(img_orig, zoom, order=0)\n voxelsize_orig = self.voxelsize\n logger.debug(\"zoom %s\", zoom)\n logger.debug(\"vs %s\", self.voxelsize)\n self.voxelsize = self.voxelsize * zoom\n\n # self.img = resize_to_shape_with_zoom(img_orig, loseeds.shape, 1.0 / ms_zoom, order=0)\n\n # this step set the self.segmentation\n self.__single_scale_gc_run()\n # logger.debug(\n # 'segmentation - max: %d min: %d' % (\n # np.max(self.segmentation),\n # np.min(self.segmentation)\n # )\n # )\n logger.debug(\n \"segmentation: %s\", scipy.stats.describe(self.segmentation, axis=None)\n )\n\n self.modelparams = modelparams_hi\n self.voxelsize = voxelsize_orig\n self.img = img_orig\n self.seeds = hiseeds\n self.stats[\"t2\"] = time.time() - start\n return hard_constraints", "def run(self, run_fit_model=True):\n \"\"\"\n Run the Graph Cut segmentation according to preset parameters.\n\n :param run_fit_model: Allow to skip model fit when the model is prepared before\n :return:\n \"\"\"\n\n if run_fit_model:\n self.fit_model(self.img, self.voxelsize, self.seeds)\n\n self._start_time = time.time()\n if self.segparams[\"method\"].lower() in (\"graphcut\", \"gc\"):\n self.__single_scale_gc_run()\n elif self.segparams[\"method\"].lower() in (\n \"multiscale_graphcut\",\n \"multiscale_gc\",\n \"msgc\",\n \"msgc_lo2hi\",\n \"lo2hi\",\n \"multiscale_graphcut_lo2hi\",\n ):\n logger.debug(\"performing multiscale Graph-Cut lo2hi\")\n self.__multiscale_gc_lo2hi_run()\n elif self.segparams[\"method\"].lower() in (\n \"msgc_hi2lo\",\n \"hi2lo\",\n \"multiscale_graphcut_hi2lo\",\n ):\n logger.debug(\"performing multiscale Graph-Cut hi2lo\")\n self.__multiscale_gc_hi2lo_run()\n else:\n logger.error(\"Unknown segmentation method: \" + self.segparams[\"method\"])", "def __msgc_step3_discontinuity_localization(self):\n \"\"\"\n Estimate discontinuity in basis of low resolution image segmentation.\n :return: discontinuity in low resolution\n \"\"\"\n import scipy\n\n start = self._start_time\n seg = 1 - self.segmentation.astype(np.int8)\n self.stats[\"low level object voxels\"] = np.sum(seg)\n self.stats[\"low level image voxels\"] = np.prod(seg.shape)\n # in seg is now stored low resolution segmentation\n # back to normal parameters\n # step 2: discontinuity localization\n # self.segparams = sparams_hi\n seg_border = scipy.ndimage.filters.laplace(seg, mode=\"constant\")\n logger.debug(\"seg_border: %s\", scipy.stats.describe(seg_border, axis=None))\n # logger.debug(str(np.max(seg_border)))\n # logger.debug(str(np.min(seg_border)))\n seg_border[seg_border != 0] = 1\n logger.debug(\"seg_border: %s\", scipy.stats.describe(seg_border, axis=None))\n # scipy.ndimage.morphology.distance_transform_edt\n boundary_dilatation_distance = self.segparams[\"boundary_dilatation_distance\"]\n seg = scipy.ndimage.morphology.binary_dilation(\n seg_border,\n # seg,\n np.ones(\n [\n (boundary_dilatation_distance * 2) + 1,\n (boundary_dilatation_distance * 2) + 1,\n (boundary_dilatation_distance * 2) + 1,\n ]\n ),\n )\n if self.keep_temp_properties:\n self.temp_msgc_lowres_discontinuity = seg\n else:\n self.temp_msgc_lowres_discontinuity = None\n\n if self.debug_images:\n import sed3\n\n pd = sed3.sed3(seg_border) # ), contour=seg)\n pd.show()\n pd = sed3.sed3(seg) # ), contour=seg)\n pd.show()\n # segzoom = scipy.ndimage.interpolation.zoom(seg.astype('float'), zoom,\n # order=0).astype('int8')\n self.stats[\"t3\"] = time.time() - start\n return seg", "def _cnvkit_segment(cnr_file, cov_interval, data, items, out_file=None, detailed=False):\n \"\"\"Perform segmentation and copy number calling on normalized inputs\n \"\"\"\n if not out_file:\n out_file = \"%s.cns\" % os.path.splitext(cnr_file)[0]\n if not utils.file_uptodate(out_file, cnr_file):\n with file_transaction(data, out_file) as tx_out_file:\n if not _cna_has_values(cnr_file):\n with open(tx_out_file, \"w\") as out_handle:\n out_handle.write(\"chromosome\\tstart\\tend\\tgene\\tlog2\\tprobes\\tCN1\\tCN2\\tbaf\\tweight\\n\")\n else:\n # Scale cores to avoid memory issues with segmentation\n # https://github.com/etal/cnvkit/issues/346\n if cov_interval == \"genome\":\n cores = max(1, dd.get_cores(data) // 2)\n else:\n cores = dd.get_cores(data)\n cmd = [_get_cmd(), \"segment\", \"-p\", str(cores), \"-o\", tx_out_file, cnr_file]\n small_vrn_files = _compatible_small_variants(data, items)\n if len(small_vrn_files) > 0 and _cna_has_values(cnr_file) and cov_interval != \"genome\":\n cmd += [\"--vcf\", small_vrn_files[0].name, \"--sample-id\", small_vrn_files[0].sample]\n if small_vrn_files[0].normal:\n cmd += [\"--normal-id\", small_vrn_files[0].normal]\n resources = config_utils.get_resources(\"cnvkit_segment\", data[\"config\"])\n user_options = resources.get(\"options\", [])\n cmd += [str(x) for x in user_options]\n if cov_interval == \"genome\" and \"--threshold\" not in user_options:\n cmd += [\"--threshold\", \"0.00001\"]\n # For tumors, remove very low normalized regions, avoiding upcaptured noise\n # https://github.com/bcbio/bcbio-nextgen/issues/2171#issuecomment-348333650\n # unless we want detailed segmentation for downstream tools\n paired = vcfutils.get_paired(items)\n if paired:\n #if detailed:\n # cmd += [\"-m\", \"hmm-tumor\"]\n if \"--drop-low-coverage\" not in user_options:\n cmd += [\"--drop-low-coverage\"]\n # preferentially use conda installed Rscript\n export_cmd = (\"%s && export TMPDIR=%s && \"\n % (utils.get_R_exports(), os.path.dirname(tx_out_file)))\n do.run(export_cmd + \" \".join(cmd), \"CNVkit segment\")\n return out_file", "def _setup_gc2_framework(self):\n \"\"\"\n This method establishes the GC2 framework for a multi-segment\n (and indeed multi-typology) case based on the description in\n Spudich & Chiou (2015) - see section on Generalized Coordinate\n System for Multiple Rupture Traces\n \"\"\"\n # Generate cartesian edge set\n edge_sets = self._get_cartesian_edge_set()\n self.gc2_config = {}\n # Determine furthest two points apart\n endpoint_set = numpy.vstack([cep for cep in self.cartesian_endpoints])\n dmat = squareform(pdist(endpoint_set))\n irow, icol = numpy.unravel_index(numpy.argmax(dmat), dmat.shape)\n # Join further points to form a vector (a_hat in Spudich & Chiou)\n # According to Spudich & Chiou, a_vec should be eastward trending\n if endpoint_set[irow, 0] > endpoint_set[icol, 0]:\n # Row point is to the east of column point\n beginning = endpoint_set[icol, :2]\n ending = endpoint_set[irow, :2]\n else:\n # Column point is to the east of row point\n beginning = endpoint_set[irow, :2]\n ending = endpoint_set[icol, :2]\n\n # Convert to unit vector\n a_vec = ending - beginning\n self.gc2_config[\"a_hat\"] = a_vec / numpy.linalg.norm(a_vec)\n # Get e_j set\n self.gc2_config[\"ejs\"] = []\n for c_edges in self.cartesian_edges:\n self.gc2_config[\"ejs\"].append(\n numpy.dot(c_edges[-1, :2] - c_edges[0, :2],\n self.gc2_config[\"a_hat\"]))\n # A \"total E\" is defined as the sum of the e_j values\n self.gc2_config[\"e_tot\"] = sum(self.gc2_config[\"ejs\"])\n sign_etot = numpy.sign(self.gc2_config[\"e_tot\"])\n b_vec = numpy.zeros(2)\n self.gc2_config[\"sign\"] = []\n for i, c_edges in enumerate(self.cartesian_edges):\n segment_sign = numpy.sign(self.gc2_config[\"ejs\"][i]) * sign_etot\n self.gc2_config[\"sign\"].append(segment_sign)\n if segment_sign < 0:\n # Segment is discordant - reverse the points\n c_edges = numpy.flipud(c_edges)\n self.cartesian_edges[i] = c_edges\n self.cartesian_endpoints[i] = numpy.flipud(\n self.cartesian_endpoints[i])\n b_vec += (c_edges[-1, :2] - c_edges[0, :2])\n\n # Get unit vector\n self.gc2_config[\"b_hat\"] = b_vec / numpy.linalg.norm(b_vec)\n if numpy.dot(a_vec, self.gc2_config[\"b_hat\"]) >= 0.0:\n self.p0 = beginning\n else:\n self.p0 = ending\n # To later calculate Ry0 it is necessary to determine the maximum\n # GC2-U coordinate for the fault\n self._get_gc2_coordinates_for_rupture(edge_sets)", "def graphcut_stawiaski(regions, gradient = False, foreground = False, background = False):\n \"\"\"\n Executes a Stawiaski label graph cut.\n \n Parameters\n ----------\n regions : ndarray\n The regions image / label map.\n gradient : ndarray\n The gradient image.\n foreground : ndarray\n The foreground markers.\n background : ndarray\n The background markers.\n \n Returns\n -------\n segmentation : ndarray\n The graph-cut segmentation result as boolean array.\n \n Raises\n ------\n ArgumentError\n When the supplied data is erroneous.\n \"\"\"\n # initialize logger\n logger = Logger.getInstance()\n \n # unpack images if required\n # !TODO: This is an ugly hack, especially since it can be seen inside the function definition\n # How to overcome this, since I can not use a wrapper function as the whole thing must be pickable\n if not gradient and not foreground and not background: \n regions, gradient, foreground, background = regions\n \n # ensure that input images are scipy arrays\n img_region = scipy.asarray(regions)\n img_gradient = scipy.asarray(gradient)\n img_fg = scipy.asarray(foreground, dtype=scipy.bool_)\n img_bg = scipy.asarray(background, dtype=scipy.bool_)\n \n # ensure correctness of supplied images\n if not (img_region.shape == img_gradient.shape == img_fg.shape == img_bg.shape): raise ArgumentError('All supplied images must be of the same shape.')\n\n # recompute the label ids to start from id = 1\n img_region = relabel(img_region)\n \n # generate graph\n gcgraph = graph_from_labels(img_region, img_fg, img_bg, boundary_term = boundary_stawiaski, boundary_term_args = (img_gradient))\n \n # execute min-cut\n maxflow = gcgraph.maxflow() # executes the cut and returns the maxflow value\n \n logger.debug('Graph-cut terminated successfully with maxflow of {}.'.format(maxflow))\n \n # apply results to the region image\n mapping = [0] # no regions with id 1 exists in mapping, entry used as padding\n mapping.extend([0 if gcgraph.termtype.SINK == gcgraph.what_segment(int(x) - 1) else 1 for x in scipy.unique(img_region)])\n img_results = relabel_map(img_region, mapping)\n \n return img_results.astype(scipy.bool_)", "def segment(self, document):\n \"\"\"\n document: list[str]\n return list[int],\n i-th element denotes whether exists a boundary right before paragraph i(0 indexed)\n \"\"\"\n # ensure document is not empty and every element is an instance of str\n assert(len(document) > 0 and len([d for d in document if not isinstance(d, str)]) == 0)\n # step 1, do preprocessing\n n = len(document)\n self.window = max(min(self.window, n / 3), 1)\n cnts = [Counter(self.tokenizer.tokenize(document[i])) for i in range(n)]\n\n # step 2, calculate gap score\n gap_score = [0 for _ in range(n)]\n for i in range(n):\n sz = min(min(i + 1, n - i - 1), self.window)\n lcnt, rcnt = Counter(), Counter()\n for j in range(i - sz + 1, i + 1):\n lcnt += cnts[j]\n for j in range(i + 1, i + sz + 1):\n rcnt += cnts[j]\n gap_score[i] = cosine_sim(lcnt, rcnt)\n\n # step 3, calculate depth score\n depth_score = [0 for _ in range(n)]\n for i in range(n):\n if i < self.window or i + self.window >= n:\n continue\n ptr = i - 1\n while ptr >= 0 and gap_score[ptr] >= gap_score[ptr + 1]:\n ptr -= 1\n lval = gap_score[ptr + 1]\n ptr = i + 1\n while ptr < n and gap_score[ptr] >= gap_score[ptr - 1]:\n ptr += 1\n rval = gap_score[ptr - 1]\n depth_score[i] = lval + rval - 2 * gap_score[i]\n\n # step 4, smooth depth score with fixed window size 3\n smooth_dep_score = [0 for _ in range(n)]\n for i in range(n):\n if i - 1 < 0 or i + 1 >= n:\n smooth_dep_score[i] = depth_score[i]\n else:\n smooth_dep_score[i] = np.average(depth_score[(i - 1):(i + 2)])\n\n # step 5, determine boundaries\n boundaries = [0 for _ in range(n)]\n avg = np.average(smooth_dep_score)\n stdev = np.std(smooth_dep_score)\n cutoff = avg - stdev / 2.0\n\n depth_tuples = list(zip(smooth_dep_score, list(range(len(smooth_dep_score)))))\n depth_tuples.sort()\n depth_tuples.reverse()\n hp = [x for x in depth_tuples if (x[0] > cutoff)]\n for dt in hp:\n boundaries[dt[1]] = 1\n for i in range(dt[1] - 4, dt[1] + 4 + 1):\n if i != dt[1] and i >= 0 and i < n and boundaries[i] == 1:\n boundaries[dt[1]] = 0\n break\n return [1] + boundaries[:-1]", "def model_segments(copy_file, work_dir, paired):\n \"\"\"Perform segmentation on input copy number log2 ratio file.\n \"\"\"\n out_file = os.path.join(work_dir, \"%s.cr.seg\" % dd.get_sample_name(paired.tumor_data))\n tumor_counts, normal_counts = heterogzygote_counts(paired)\n if not utils.file_exists(out_file):\n with file_transaction(paired.tumor_data, out_file) as tx_out_file:\n params = [\"-T\", \"ModelSegments\",\n \"--denoised-copy-ratios\", copy_file,\n \"--allelic-counts\", tumor_counts,\n \"--output-prefix\", dd.get_sample_name(paired.tumor_data),\n \"-O\", os.path.dirname(tx_out_file)]\n if normal_counts:\n params += [\"--normal-allelic-counts\", normal_counts]\n _run_with_memory_scaling(params, tx_out_file, paired.tumor_data)\n for tx_fname in glob.glob(os.path.join(os.path.dirname(tx_out_file),\n \"%s*\" % dd.get_sample_name(paired.tumor_data))):\n shutil.copy(tx_fname, os.path.join(work_dir, os.path.basename(tx_fname)))\n return {\"seg\": out_file, \"tumor_hets\": out_file.replace(\".cr.seg\", \".hets.tsv\"),\n \"final_seg\": out_file.replace(\".cr.seg\", \".modelFinal.seg\")}", "def correct_segmentation(segments, clusters, min_time):\n \"\"\" Corrects the predicted segmentation\n\n This process prevents over segmentation\n\n Args:\n segments (:obj:`list` of :obj:`list` of :obj:`Point`):\n segments to correct\n min_time (int): minimum required time for segmentation\n \"\"\"\n # segments = [points for points in segments if len(points) > 1]\n\n result_segments = []\n prev_segment = None\n for i, segment in enumerate(segments):\n if len(segment) >= 1:\n continue\n\n cluster = clusters[i]\n if prev_segment is None:\n prev_segment = segment\n else:\n cluster_dt = 0\n if len(cluster) > 0:\n cluster_dt = abs(cluster[0].time_difference(cluster[-1]))\n if cluster_dt <= min_time:\n prev_segment.extend(segment)\n else:\n prev_segment.append(segment[0])\n result_segments.append(prev_segment)\n prev_segment = segment\n if prev_segment is not None:\n result_segments.append(prev_segment)\n\n return result_segments", "def boundary_stawiaski(graph, label_image, gradient_image): # label image is not required to hold continuous ids or to start from 1\n r\"\"\"\n Boundary term based on the sum of border voxel pairs differences.\n \n An implementation of the boundary term in [1]_, suitable to be used with the `~medpy.graphcut.generate.graph_from_labels` function.\n \n Determines for each two supplied regions the voxels forming their border assuming\n :math:`ndim*2`-connectedness (e.g. :math:`3*2=6` for 3D). From the gradient magnitude values of each\n end-point voxel the border-voxel pairs, the highest one is selected and passed to a\n strictly positive and decreasing function :math:`g(x)`, which is defined as:\n \n .. math::\n \n g(x) = \\left(\\frac{1}{1+|x|}\\right)^k\n \n ,where :math:`k=2`. The final weight :math:`w_{i,j}` between two regions :math:`r_i` and\n :math:`r_j` is then determined by the sum of all these neighbour values:\n \n .. math::\n \n w_{i,j} = \\sum_{e_{m,n}\\in F_{(r_i,r_j)}}g(\\max(|I(m)|,|I(n)|))\n \n , where :math:`F_{(r_i,r_j)}` is the set of border voxel-pairs :math:`e_{m,n}` between\n the regions :math:`r_i` and :math:`r_j` and :math:`|I(p)|` the absolute of the gradient\n magnitude at the voxel :math:`p`\n \n This boundary_function works as an edge indicator in the original image. In simpler\n words the weight (and therefore the energy) is obtained by summing the local contrast\n along the boundaries between two regions.\n \n Parameters\n ----------\n graph : GCGraph\n The graph to add the weights to.\n label_image : ndarray\n The label image. Must contain consecutively labelled regions starting from index 1.\n gradient_image : ndarray\n The gradient image.\n \n Notes\n -----\n This function requires the gradient magnitude image of the original image to be passed\n along. That means that `~medpy.graphcut.generate.graph_from_labels` has to be called\n with ``boundary_term_args`` set to the gradient image. This can be obtained e.g. with\n `generic_gradient_magnitude` and `prewitt` from `scipy.ndimage`.\n \n This function is tested on 2D and 3D images and theoretically works for all dimensionalities. \n \n References\n ----------\n .. [1] Stawiaski J., Decenciere E., Bidlaut F. \"Interactive Liver Tumor Segmentation\n Using Graph-cuts and watershed\" MICCAI 2008 participation\n \"\"\"\n # convert to arrays if necessary\n label_image = scipy.asarray(label_image)\n gradient_image = scipy.asarray(gradient_image)\n \n if label_image.flags['F_CONTIGUOUS']: # strangely, this one is required to be ctype ordering\n label_image = scipy.ascontiguousarray(label_image)\n \n __check_label_image(label_image)\n \n for dim in range(label_image.ndim):\n # prepare slicer for all minus last and all minus first \"row\"\n slicer_from = [slice(None)] * label_image.ndim\n slicer_to = [slice(None)] * label_image.ndim\n slicer_from[dim] = slice(None, -1)\n slicer_to[dim] = slice(1, None)\n # slice views of keys\n keys_from = label_image[slicer_from]\n keys_to = label_image[slicer_to]\n # determine not equal keys\n valid_edges = keys_from != keys_to\n # determine largest gradient\n gradient_max = numpy.maximum(numpy.abs(gradient_image[slicer_from]), numpy.abs(gradient_image[slicer_to]))[valid_edges]\n # determine key order\n keys_max = numpy.maximum(keys_from, keys_to)[valid_edges]\n keys_min = numpy.minimum(keys_from, keys_to)[valid_edges]\n # set edges / nweights\n for k1, k2, val in zip(keys_min, keys_max, gradient_max):\n weight = math.pow(1./(1. + val), 2) # weight contribution of a single pixel\n weight = max(weight, sys.float_info.min)\n graph.set_nweight(k1 - 1 , k2 - 1, weight, weight)", "def __ms_npenalty_fcn(self, axis, mask, orig_shape):\n \"\"\"\n :param axis: direction of edge\n :param mask: 3d ndarray with ones where is fine resolution\n\n Neighboorhood penalty between small pixels should be smaller then in\n bigger tiles. This is the way how to set it.\n\n \"\"\"\n maskz = zoom_to_shape(mask, orig_shape)\n\n maskz_new = np.zeros(orig_shape, dtype=np.int16)\n maskz_new[maskz == 0] = self._msgc_npenalty_table[0, axis]\n maskz_new[maskz == 1] = self._msgc_npenalty_table[1, axis]\n # import sed3\n # ed = sed3.sed3(maskz_new)\n # import ipdb; ipdb.set_trace() # noqa BREAKPOINT\n\n return maskz_new" ]
[ 0.8354851007461548, 0.717715322971344, 0.7040823698043823, 0.6870102882385254, 0.6714046597480774, 0.6607586145401001, 0.6603902578353882, 0.6547603011131287, 0.6508672833442688, 0.6498038172721863, 0.6489167213439941, 0.641808032989502 ]
Run Graph-Cut segmentation with simplifiyng of high resolution multiscale graph. In first step is performed normal GC on low resolution data Second step construct finer grid on edges of segmentation from first step. There is no option for use without `use_boundary_penalties`
def __multiscale_gc_hi2lo_run(self): # , pyed): """ Run Graph-Cut segmentation with simplifiyng of high resolution multiscale graph. In first step is performed normal GC on low resolution data Second step construct finer grid on edges of segmentation from first step. There is no option for use without `use_boundary_penalties` """ # from PyQt4.QtCore import pyqtRemoveInputHook # pyqtRemoveInputHook() self.__msgc_step0_init() hard_constraints = self.__msgc_step12_low_resolution_segmentation() # ===== high resolution data processing seg = self.__msgc_step3_discontinuity_localization() nlinks, unariesalt2, msinds = self.__msgc_step45678_hi2lo_construct_graph( hard_constraints, seg ) self.__msgc_step9_finish_perform_gc_and_reshape(nlinks, unariesalt2, msinds)
[ "def __multiscale_gc_lo2hi_run(self): # , pyed):\n \"\"\"\n Run Graph-Cut segmentation with refinement of low resolution multiscale graph.\n In first step is performed normal GC on low resolution data\n Second step construct finer grid on edges of segmentation from first\n step.\n There is no option for use without `use_boundary_penalties`\n \"\"\"\n # from PyQt4.QtCore import pyqtRemoveInputHook\n # pyqtRemoveInputHook()\n self._msgc_lo2hi_resize_init()\n self.__msgc_step0_init()\n\n hard_constraints = self.__msgc_step12_low_resolution_segmentation()\n # ===== high resolution data processing\n seg = self.__msgc_step3_discontinuity_localization()\n\n self.stats[\"t3.1\"] = (time.time() - self._start_time)\n graph = Graph(\n seg,\n voxelsize=self.voxelsize,\n nsplit=self.segparams[\"block_size\"],\n edge_weight_table=self._msgc_npenalty_table,\n compute_low_nodes_index=True,\n )\n\n # graph.run() = graph.generate_base_grid() + graph.split_voxels()\n # graph.run()\n graph.generate_base_grid()\n self.stats[\"t3.2\"] = (time.time() - self._start_time)\n graph.split_voxels()\n\n self.stats[\"t3.3\"] = (time.time() - self._start_time)\n\n self.stats.update(graph.stats)\n self.stats[\"t4\"] = (time.time() - self._start_time)\n mul_mask, mul_val = self.__msgc_tlinks_area_weight_from_low_segmentation(seg)\n area_weight = 1\n unariesalt = self.__create_tlinks(\n self.img,\n self.voxelsize,\n self.seeds,\n area_weight=area_weight,\n hard_constraints=hard_constraints,\n mul_mask=None,\n mul_val=None,\n )\n # N-links prepared\n self.stats[\"t5\"] = (time.time() - self._start_time)\n un, ind = np.unique(graph.msinds, return_index=True)\n self.stats[\"t6\"] = (time.time() - self._start_time)\n\n self.stats[\"t7\"] = (time.time() - self._start_time)\n unariesalt2_lo2hi = np.hstack(\n [unariesalt[ind, 0, 0].reshape(-1, 1), unariesalt[ind, 0, 1].reshape(-1, 1)]\n )\n nlinks_lo2hi = np.hstack([graph.edges, graph.edges_weights.reshape(-1, 1)])\n if self.debug_images:\n import sed3\n\n ed = sed3.sed3(unariesalt[:, :, 0].reshape(self.img.shape))\n ed.show()\n import sed3\n\n ed = sed3.sed3(unariesalt[:, :, 1].reshape(self.img.shape))\n ed.show()\n # ed = sed3.sed3(seg)\n # ed.show()\n # import sed3\n # ed = sed3.sed3(graph.data)\n # ed.show()\n # import sed3\n # ed = sed3.sed3(graph.msinds)\n # ed.show()\n\n # nlinks, unariesalt2, msinds = self.__msgc_step45678_construct_graph(area_weight, hard_constraints, seg)\n # self.__msgc_step9_finish_perform_gc_and_reshape(nlinks, unariesalt2, msinds)\n self.__msgc_step9_finish_perform_gc_and_reshape(\n nlinks_lo2hi, unariesalt2_lo2hi, graph.msinds\n )\n self._msgc_lo2hi_resize_clean_finish()", "def __msgc_step12_low_resolution_segmentation(self):\n \"\"\"\n Get the segmentation and the\n :return:\n \"\"\"\n import scipy\n\n start = self._start_time\n # ===== low resolution data processing\n # default parameters\n # TODO segparams_lo and segparams_hi je tam asi zbytecně\n sparams_lo = {\n \"boundary_dilatation_distance\": 2,\n \"block_size\": 6,\n \"use_boundary_penalties\": True,\n \"boundary_penalties_weight\": 1,\n \"tile_zoom_constant\": 1,\n }\n\n sparams_lo.update(self.segparams)\n sparams_hi = copy.copy(sparams_lo)\n # sparams_lo['boundary_penalties_weight'] = (\n # sparams_lo['boundary_penalties_weight'] *\n # sparams_lo['block_size'])\n self.segparams = sparams_lo\n\n self.stats[\"t1\"] = time.time() - start\n # step 1: low res GC\n hiseeds = self.seeds\n # ms_zoom = 4 # 0.125 #self.segparams['scale']\n # ms_zoom = self.segparams['block_size']\n # loseeds = pyed.getSeeds()\n # logger.debug(\"msc \" + str(np.unique(hiseeds)))\n loseeds = seed_zoom(hiseeds, self.segparams[\"block_size\"])\n\n hard_constraints = True\n\n self.seeds = loseeds\n\n modelparams_hi = self.modelparams.copy()\n # feature vector will be computed from selected voxels\n self.modelparams[\"use_extra_features_for_training\"] = True\n\n # TODO what with voxels? It is used from here\n # hiseeds and hiimage is used to create intensity model\n self.voxels1 = self.img[hiseeds == 1].reshape(-1, 1)\n self.voxels2 = self.img[hiseeds == 2].reshape(-1, 1)\n # this is how to compute with loseeds resolution but in wrong way\n # self.voxels1 = self.img[self.seeds == 1]\n # self.voxels2 = self.img[self.seeds == 2]\n\n # self.voxels1 = pyed.getSeedsVal(1)\n # self.voxels2 = pyed.getSeedsVal(2)\n\n img_orig = self.img\n\n # TODO this should be done with resize_to_shape_whith_zoom\n zoom = np.asarray(loseeds.shape).astype(np.float) / img_orig.shape\n self.img = scipy.ndimage.interpolation.zoom(img_orig, zoom, order=0)\n voxelsize_orig = self.voxelsize\n logger.debug(\"zoom %s\", zoom)\n logger.debug(\"vs %s\", self.voxelsize)\n self.voxelsize = self.voxelsize * zoom\n\n # self.img = resize_to_shape_with_zoom(img_orig, loseeds.shape, 1.0 / ms_zoom, order=0)\n\n # this step set the self.segmentation\n self.__single_scale_gc_run()\n # logger.debug(\n # 'segmentation - max: %d min: %d' % (\n # np.max(self.segmentation),\n # np.min(self.segmentation)\n # )\n # )\n logger.debug(\n \"segmentation: %s\", scipy.stats.describe(self.segmentation, axis=None)\n )\n\n self.modelparams = modelparams_hi\n self.voxelsize = voxelsize_orig\n self.img = img_orig\n self.seeds = hiseeds\n self.stats[\"t2\"] = time.time() - start\n return hard_constraints", "def run(self, run_fit_model=True):\n \"\"\"\n Run the Graph Cut segmentation according to preset parameters.\n\n :param run_fit_model: Allow to skip model fit when the model is prepared before\n :return:\n \"\"\"\n\n if run_fit_model:\n self.fit_model(self.img, self.voxelsize, self.seeds)\n\n self._start_time = time.time()\n if self.segparams[\"method\"].lower() in (\"graphcut\", \"gc\"):\n self.__single_scale_gc_run()\n elif self.segparams[\"method\"].lower() in (\n \"multiscale_graphcut\",\n \"multiscale_gc\",\n \"msgc\",\n \"msgc_lo2hi\",\n \"lo2hi\",\n \"multiscale_graphcut_lo2hi\",\n ):\n logger.debug(\"performing multiscale Graph-Cut lo2hi\")\n self.__multiscale_gc_lo2hi_run()\n elif self.segparams[\"method\"].lower() in (\n \"msgc_hi2lo\",\n \"hi2lo\",\n \"multiscale_graphcut_hi2lo\",\n ):\n logger.debug(\"performing multiscale Graph-Cut hi2lo\")\n self.__multiscale_gc_hi2lo_run()\n else:\n logger.error(\"Unknown segmentation method: \" + self.segparams[\"method\"])", "def __msgc_step3_discontinuity_localization(self):\n \"\"\"\n Estimate discontinuity in basis of low resolution image segmentation.\n :return: discontinuity in low resolution\n \"\"\"\n import scipy\n\n start = self._start_time\n seg = 1 - self.segmentation.astype(np.int8)\n self.stats[\"low level object voxels\"] = np.sum(seg)\n self.stats[\"low level image voxels\"] = np.prod(seg.shape)\n # in seg is now stored low resolution segmentation\n # back to normal parameters\n # step 2: discontinuity localization\n # self.segparams = sparams_hi\n seg_border = scipy.ndimage.filters.laplace(seg, mode=\"constant\")\n logger.debug(\"seg_border: %s\", scipy.stats.describe(seg_border, axis=None))\n # logger.debug(str(np.max(seg_border)))\n # logger.debug(str(np.min(seg_border)))\n seg_border[seg_border != 0] = 1\n logger.debug(\"seg_border: %s\", scipy.stats.describe(seg_border, axis=None))\n # scipy.ndimage.morphology.distance_transform_edt\n boundary_dilatation_distance = self.segparams[\"boundary_dilatation_distance\"]\n seg = scipy.ndimage.morphology.binary_dilation(\n seg_border,\n # seg,\n np.ones(\n [\n (boundary_dilatation_distance * 2) + 1,\n (boundary_dilatation_distance * 2) + 1,\n (boundary_dilatation_distance * 2) + 1,\n ]\n ),\n )\n if self.keep_temp_properties:\n self.temp_msgc_lowres_discontinuity = seg\n else:\n self.temp_msgc_lowres_discontinuity = None\n\n if self.debug_images:\n import sed3\n\n pd = sed3.sed3(seg_border) # ), contour=seg)\n pd.show()\n pd = sed3.sed3(seg) # ), contour=seg)\n pd.show()\n # segzoom = scipy.ndimage.interpolation.zoom(seg.astype('float'), zoom,\n # order=0).astype('int8')\n self.stats[\"t3\"] = time.time() - start\n return seg", "def _cnvkit_segment(cnr_file, cov_interval, data, items, out_file=None, detailed=False):\n \"\"\"Perform segmentation and copy number calling on normalized inputs\n \"\"\"\n if not out_file:\n out_file = \"%s.cns\" % os.path.splitext(cnr_file)[0]\n if not utils.file_uptodate(out_file, cnr_file):\n with file_transaction(data, out_file) as tx_out_file:\n if not _cna_has_values(cnr_file):\n with open(tx_out_file, \"w\") as out_handle:\n out_handle.write(\"chromosome\\tstart\\tend\\tgene\\tlog2\\tprobes\\tCN1\\tCN2\\tbaf\\tweight\\n\")\n else:\n # Scale cores to avoid memory issues with segmentation\n # https://github.com/etal/cnvkit/issues/346\n if cov_interval == \"genome\":\n cores = max(1, dd.get_cores(data) // 2)\n else:\n cores = dd.get_cores(data)\n cmd = [_get_cmd(), \"segment\", \"-p\", str(cores), \"-o\", tx_out_file, cnr_file]\n small_vrn_files = _compatible_small_variants(data, items)\n if len(small_vrn_files) > 0 and _cna_has_values(cnr_file) and cov_interval != \"genome\":\n cmd += [\"--vcf\", small_vrn_files[0].name, \"--sample-id\", small_vrn_files[0].sample]\n if small_vrn_files[0].normal:\n cmd += [\"--normal-id\", small_vrn_files[0].normal]\n resources = config_utils.get_resources(\"cnvkit_segment\", data[\"config\"])\n user_options = resources.get(\"options\", [])\n cmd += [str(x) for x in user_options]\n if cov_interval == \"genome\" and \"--threshold\" not in user_options:\n cmd += [\"--threshold\", \"0.00001\"]\n # For tumors, remove very low normalized regions, avoiding upcaptured noise\n # https://github.com/bcbio/bcbio-nextgen/issues/2171#issuecomment-348333650\n # unless we want detailed segmentation for downstream tools\n paired = vcfutils.get_paired(items)\n if paired:\n #if detailed:\n # cmd += [\"-m\", \"hmm-tumor\"]\n if \"--drop-low-coverage\" not in user_options:\n cmd += [\"--drop-low-coverage\"]\n # preferentially use conda installed Rscript\n export_cmd = (\"%s && export TMPDIR=%s && \"\n % (utils.get_R_exports(), os.path.dirname(tx_out_file)))\n do.run(export_cmd + \" \".join(cmd), \"CNVkit segment\")\n return out_file", "def graphcut_stawiaski(regions, gradient = False, foreground = False, background = False):\n \"\"\"\n Executes a Stawiaski label graph cut.\n \n Parameters\n ----------\n regions : ndarray\n The regions image / label map.\n gradient : ndarray\n The gradient image.\n foreground : ndarray\n The foreground markers.\n background : ndarray\n The background markers.\n \n Returns\n -------\n segmentation : ndarray\n The graph-cut segmentation result as boolean array.\n \n Raises\n ------\n ArgumentError\n When the supplied data is erroneous.\n \"\"\"\n # initialize logger\n logger = Logger.getInstance()\n \n # unpack images if required\n # !TODO: This is an ugly hack, especially since it can be seen inside the function definition\n # How to overcome this, since I can not use a wrapper function as the whole thing must be pickable\n if not gradient and not foreground and not background: \n regions, gradient, foreground, background = regions\n \n # ensure that input images are scipy arrays\n img_region = scipy.asarray(regions)\n img_gradient = scipy.asarray(gradient)\n img_fg = scipy.asarray(foreground, dtype=scipy.bool_)\n img_bg = scipy.asarray(background, dtype=scipy.bool_)\n \n # ensure correctness of supplied images\n if not (img_region.shape == img_gradient.shape == img_fg.shape == img_bg.shape): raise ArgumentError('All supplied images must be of the same shape.')\n\n # recompute the label ids to start from id = 1\n img_region = relabel(img_region)\n \n # generate graph\n gcgraph = graph_from_labels(img_region, img_fg, img_bg, boundary_term = boundary_stawiaski, boundary_term_args = (img_gradient))\n \n # execute min-cut\n maxflow = gcgraph.maxflow() # executes the cut and returns the maxflow value\n \n logger.debug('Graph-cut terminated successfully with maxflow of {}.'.format(maxflow))\n \n # apply results to the region image\n mapping = [0] # no regions with id 1 exists in mapping, entry used as padding\n mapping.extend([0 if gcgraph.termtype.SINK == gcgraph.what_segment(int(x) - 1) else 1 for x in scipy.unique(img_region)])\n img_results = relabel_map(img_region, mapping)\n \n return img_results.astype(scipy.bool_)", "def _setup_gc2_framework(self):\n \"\"\"\n This method establishes the GC2 framework for a multi-segment\n (and indeed multi-typology) case based on the description in\n Spudich & Chiou (2015) - see section on Generalized Coordinate\n System for Multiple Rupture Traces\n \"\"\"\n # Generate cartesian edge set\n edge_sets = self._get_cartesian_edge_set()\n self.gc2_config = {}\n # Determine furthest two points apart\n endpoint_set = numpy.vstack([cep for cep in self.cartesian_endpoints])\n dmat = squareform(pdist(endpoint_set))\n irow, icol = numpy.unravel_index(numpy.argmax(dmat), dmat.shape)\n # Join further points to form a vector (a_hat in Spudich & Chiou)\n # According to Spudich & Chiou, a_vec should be eastward trending\n if endpoint_set[irow, 0] > endpoint_set[icol, 0]:\n # Row point is to the east of column point\n beginning = endpoint_set[icol, :2]\n ending = endpoint_set[irow, :2]\n else:\n # Column point is to the east of row point\n beginning = endpoint_set[irow, :2]\n ending = endpoint_set[icol, :2]\n\n # Convert to unit vector\n a_vec = ending - beginning\n self.gc2_config[\"a_hat\"] = a_vec / numpy.linalg.norm(a_vec)\n # Get e_j set\n self.gc2_config[\"ejs\"] = []\n for c_edges in self.cartesian_edges:\n self.gc2_config[\"ejs\"].append(\n numpy.dot(c_edges[-1, :2] - c_edges[0, :2],\n self.gc2_config[\"a_hat\"]))\n # A \"total E\" is defined as the sum of the e_j values\n self.gc2_config[\"e_tot\"] = sum(self.gc2_config[\"ejs\"])\n sign_etot = numpy.sign(self.gc2_config[\"e_tot\"])\n b_vec = numpy.zeros(2)\n self.gc2_config[\"sign\"] = []\n for i, c_edges in enumerate(self.cartesian_edges):\n segment_sign = numpy.sign(self.gc2_config[\"ejs\"][i]) * sign_etot\n self.gc2_config[\"sign\"].append(segment_sign)\n if segment_sign < 0:\n # Segment is discordant - reverse the points\n c_edges = numpy.flipud(c_edges)\n self.cartesian_edges[i] = c_edges\n self.cartesian_endpoints[i] = numpy.flipud(\n self.cartesian_endpoints[i])\n b_vec += (c_edges[-1, :2] - c_edges[0, :2])\n\n # Get unit vector\n self.gc2_config[\"b_hat\"] = b_vec / numpy.linalg.norm(b_vec)\n if numpy.dot(a_vec, self.gc2_config[\"b_hat\"]) >= 0.0:\n self.p0 = beginning\n else:\n self.p0 = ending\n # To later calculate Ry0 it is necessary to determine the maximum\n # GC2-U coordinate for the fault\n self._get_gc2_coordinates_for_rupture(edge_sets)", "def model_segments(copy_file, work_dir, paired):\n \"\"\"Perform segmentation on input copy number log2 ratio file.\n \"\"\"\n out_file = os.path.join(work_dir, \"%s.cr.seg\" % dd.get_sample_name(paired.tumor_data))\n tumor_counts, normal_counts = heterogzygote_counts(paired)\n if not utils.file_exists(out_file):\n with file_transaction(paired.tumor_data, out_file) as tx_out_file:\n params = [\"-T\", \"ModelSegments\",\n \"--denoised-copy-ratios\", copy_file,\n \"--allelic-counts\", tumor_counts,\n \"--output-prefix\", dd.get_sample_name(paired.tumor_data),\n \"-O\", os.path.dirname(tx_out_file)]\n if normal_counts:\n params += [\"--normal-allelic-counts\", normal_counts]\n _run_with_memory_scaling(params, tx_out_file, paired.tumor_data)\n for tx_fname in glob.glob(os.path.join(os.path.dirname(tx_out_file),\n \"%s*\" % dd.get_sample_name(paired.tumor_data))):\n shutil.copy(tx_fname, os.path.join(work_dir, os.path.basename(tx_fname)))\n return {\"seg\": out_file, \"tumor_hets\": out_file.replace(\".cr.seg\", \".hets.tsv\"),\n \"final_seg\": out_file.replace(\".cr.seg\", \".modelFinal.seg\")}", "def boundary_stawiaski(graph, label_image, gradient_image): # label image is not required to hold continuous ids or to start from 1\n r\"\"\"\n Boundary term based on the sum of border voxel pairs differences.\n \n An implementation of the boundary term in [1]_, suitable to be used with the `~medpy.graphcut.generate.graph_from_labels` function.\n \n Determines for each two supplied regions the voxels forming their border assuming\n :math:`ndim*2`-connectedness (e.g. :math:`3*2=6` for 3D). From the gradient magnitude values of each\n end-point voxel the border-voxel pairs, the highest one is selected and passed to a\n strictly positive and decreasing function :math:`g(x)`, which is defined as:\n \n .. math::\n \n g(x) = \\left(\\frac{1}{1+|x|}\\right)^k\n \n ,where :math:`k=2`. The final weight :math:`w_{i,j}` between two regions :math:`r_i` and\n :math:`r_j` is then determined by the sum of all these neighbour values:\n \n .. math::\n \n w_{i,j} = \\sum_{e_{m,n}\\in F_{(r_i,r_j)}}g(\\max(|I(m)|,|I(n)|))\n \n , where :math:`F_{(r_i,r_j)}` is the set of border voxel-pairs :math:`e_{m,n}` between\n the regions :math:`r_i` and :math:`r_j` and :math:`|I(p)|` the absolute of the gradient\n magnitude at the voxel :math:`p`\n \n This boundary_function works as an edge indicator in the original image. In simpler\n words the weight (and therefore the energy) is obtained by summing the local contrast\n along the boundaries between two regions.\n \n Parameters\n ----------\n graph : GCGraph\n The graph to add the weights to.\n label_image : ndarray\n The label image. Must contain consecutively labelled regions starting from index 1.\n gradient_image : ndarray\n The gradient image.\n \n Notes\n -----\n This function requires the gradient magnitude image of the original image to be passed\n along. That means that `~medpy.graphcut.generate.graph_from_labels` has to be called\n with ``boundary_term_args`` set to the gradient image. This can be obtained e.g. with\n `generic_gradient_magnitude` and `prewitt` from `scipy.ndimage`.\n \n This function is tested on 2D and 3D images and theoretically works for all dimensionalities. \n \n References\n ----------\n .. [1] Stawiaski J., Decenciere E., Bidlaut F. \"Interactive Liver Tumor Segmentation\n Using Graph-cuts and watershed\" MICCAI 2008 participation\n \"\"\"\n # convert to arrays if necessary\n label_image = scipy.asarray(label_image)\n gradient_image = scipy.asarray(gradient_image)\n \n if label_image.flags['F_CONTIGUOUS']: # strangely, this one is required to be ctype ordering\n label_image = scipy.ascontiguousarray(label_image)\n \n __check_label_image(label_image)\n \n for dim in range(label_image.ndim):\n # prepare slicer for all minus last and all minus first \"row\"\n slicer_from = [slice(None)] * label_image.ndim\n slicer_to = [slice(None)] * label_image.ndim\n slicer_from[dim] = slice(None, -1)\n slicer_to[dim] = slice(1, None)\n # slice views of keys\n keys_from = label_image[slicer_from]\n keys_to = label_image[slicer_to]\n # determine not equal keys\n valid_edges = keys_from != keys_to\n # determine largest gradient\n gradient_max = numpy.maximum(numpy.abs(gradient_image[slicer_from]), numpy.abs(gradient_image[slicer_to]))[valid_edges]\n # determine key order\n keys_max = numpy.maximum(keys_from, keys_to)[valid_edges]\n keys_min = numpy.minimum(keys_from, keys_to)[valid_edges]\n # set edges / nweights\n for k1, k2, val in zip(keys_min, keys_max, gradient_max):\n weight = math.pow(1./(1. + val), 2) # weight contribution of a single pixel\n weight = max(weight, sys.float_info.min)\n graph.set_nweight(k1 - 1 , k2 - 1, weight, weight)", "def segment(self, document):\n \"\"\"\n document: list[str]\n return list[int],\n i-th element denotes whether exists a boundary right before paragraph i(0 indexed)\n \"\"\"\n # ensure document is not empty and every element is an instance of str\n assert(len(document) > 0 and len([d for d in document if not isinstance(d, str)]) == 0)\n # step 1, do preprocessing\n n = len(document)\n self.window = max(min(self.window, n / 3), 1)\n cnts = [Counter(self.tokenizer.tokenize(document[i])) for i in range(n)]\n\n # step 2, calculate gap score\n gap_score = [0 for _ in range(n)]\n for i in range(n):\n sz = min(min(i + 1, n - i - 1), self.window)\n lcnt, rcnt = Counter(), Counter()\n for j in range(i - sz + 1, i + 1):\n lcnt += cnts[j]\n for j in range(i + 1, i + sz + 1):\n rcnt += cnts[j]\n gap_score[i] = cosine_sim(lcnt, rcnt)\n\n # step 3, calculate depth score\n depth_score = [0 for _ in range(n)]\n for i in range(n):\n if i < self.window or i + self.window >= n:\n continue\n ptr = i - 1\n while ptr >= 0 and gap_score[ptr] >= gap_score[ptr + 1]:\n ptr -= 1\n lval = gap_score[ptr + 1]\n ptr = i + 1\n while ptr < n and gap_score[ptr] >= gap_score[ptr - 1]:\n ptr += 1\n rval = gap_score[ptr - 1]\n depth_score[i] = lval + rval - 2 * gap_score[i]\n\n # step 4, smooth depth score with fixed window size 3\n smooth_dep_score = [0 for _ in range(n)]\n for i in range(n):\n if i - 1 < 0 or i + 1 >= n:\n smooth_dep_score[i] = depth_score[i]\n else:\n smooth_dep_score[i] = np.average(depth_score[(i - 1):(i + 2)])\n\n # step 5, determine boundaries\n boundaries = [0 for _ in range(n)]\n avg = np.average(smooth_dep_score)\n stdev = np.std(smooth_dep_score)\n cutoff = avg - stdev / 2.0\n\n depth_tuples = list(zip(smooth_dep_score, list(range(len(smooth_dep_score)))))\n depth_tuples.sort()\n depth_tuples.reverse()\n hp = [x for x in depth_tuples if (x[0] > cutoff)]\n for dt in hp:\n boundaries[dt[1]] = 1\n for i in range(dt[1] - 4, dt[1] + 4 + 1):\n if i != dt[1] and i >= 0 and i < n and boundaries[i] == 1:\n boundaries[dt[1]] = 0\n break\n return [1] + boundaries[:-1]", "def graphcut_split(graphcut_function, regions, gradient, foreground, background, minimal_edge_length = 100, overlap = 10, processes = None):\n \"\"\"\n Executes a graph cut by splitting the original volume into a number of sub-volumes of\n a minimal edge length. These are then processed in subprocesses.\n \n This can be significantly faster than the traditional graph cuts, but should be\n used with, as it can lead to different results. To minimize this effect, the overlap\n parameter allows control over how much the respective sub-volumes should overlap.\n \n Parameters\n ----------\n graphcut_function : function\n The graph cut to use (e.g. `graphcut_stawiaski`).\n regions : ndarray\n The regions image / label map.\n gradient : ndarray\n The gradient image.\n foreground : ndarray\n The foreground markers.\n background : ndarray\n The background markers.\n minimal_edge_length : integer\n The minimal edge length of the sub-volumes in voxels.\n overlap : integer\n The overlap (in voxels) between the generated sub-volumes.\n processes : integer or None\n The number of processes to run simultaneously, if not supplied, will be the same\n as the number of processors.\n \n Returns\n -------\n segmentation : ndarray\n The graph-cut segmentation result as boolean array.\n \"\"\"\n # initialize logger\n logger = Logger.getInstance()\n \n # ensure that input images are scipy arrays\n img_region = scipy.asarray(regions)\n img_gradient = scipy.asarray(gradient)\n img_fg = scipy.asarray(foreground, dtype=scipy.bool_)\n img_bg = scipy.asarray(background, dtype=scipy.bool_)\n \n # ensure correctness of supplied images\n if not (img_region.shape == img_gradient.shape == img_fg.shape == img_bg.shape): raise ArgumentError('All supplied images must be of the same shape.') \n \n # check and eventually enhance input parameters\n if minimal_edge_length < 10: raise ArgumentError('A minimal edge length smaller than 10 is not supported.')\n if overlap < 0: raise ArgumentError('A negative overlap is not supported.')\n if overlap >= minimal_edge_length: raise ArgumentError('The overlap is not allowed to exceed the minimal edge length.')\n \n # compute how to split the volumes into sub-volumes i.e. determine step-size for each image dimension\n shape = list(img_region.shape)\n steps = [x // minimal_edge_length for x in shape]\n steps = [1 if 0 == x else x for x in steps] # replace zeros by ones\n stepsizes = [math.ceil(x / y) for x, y in zip(shape, steps)]\n logger.debug('Using a minimal edge length of {}, a sub-volume size of {} was determined from the shape {}, which means {} sub-volumes.'.format(minimal_edge_length, stepsizes, shape, reduce(lambda x, y: x*y, steps)))\n \n # control step-sizes to definitely cover the whole image\n covered_shape = [x * y for x, y in zip(steps, stepsizes)]\n for c, o in zip(covered_shape, shape):\n if c < o: raise Exception(\"The computed sub-volumes do not cover the complete image!\")\n \n # iterate over the steps and extract subvolumes according to the stepsizes\n slicer_steps = [list(range(0, int(step * stepsize), int(stepsize))) for step, stepsize in zip(steps, stepsizes)]\n slicers = [[slice(_from, _from + _offset + overlap) for _from, _offset in zip(slicer_step, stepsizes)] for slicer_step in itertools.product(*slicer_steps)]\n subvolumes_input = [(img_region[slicer],\n img_gradient[slicer],\n img_fg[slicer],\n img_bg[slicer]) for slicer in slicers]\n \n # execute the graph cuts and collect results\n subvolumes_output = graphcut_subprocesses(graphcut_function, subvolumes_input, processes)\n \n # put back data together\n img_result = scipy.zeros(img_region.shape, dtype=scipy.bool_)\n for slicer, subvolume in zip(slicers, subvolumes_output):\n sslicer_antioverlap = [slice(None)] * img_result.ndim\n \n # treat overlap area using logical-and (&)\n for dim in range(img_result.ndim):\n if 0 == slicer[dim].start: continue\n sslicer_antioverlap[dim] = slice(overlap, None)\n sslicer_overlap = [slice(None)] * img_result.ndim\n sslicer_overlap[dim] = slice(0, overlap)\n img_result[slicer][sslicer_overlap] = scipy.logical_and(img_result[slicer][sslicer_overlap], subvolume[sslicer_overlap])\n \n # treat remainder through assignment\n img_result[slicer][sslicer_antioverlap] = subvolume[sslicer_antioverlap]\n \n return img_result.astype(scipy.bool_)", "def correct_segmentation(segments, clusters, min_time):\n \"\"\" Corrects the predicted segmentation\n\n This process prevents over segmentation\n\n Args:\n segments (:obj:`list` of :obj:`list` of :obj:`Point`):\n segments to correct\n min_time (int): minimum required time for segmentation\n \"\"\"\n # segments = [points for points in segments if len(points) > 1]\n\n result_segments = []\n prev_segment = None\n for i, segment in enumerate(segments):\n if len(segment) >= 1:\n continue\n\n cluster = clusters[i]\n if prev_segment is None:\n prev_segment = segment\n else:\n cluster_dt = 0\n if len(cluster) > 0:\n cluster_dt = abs(cluster[0].time_difference(cluster[-1]))\n if cluster_dt <= min_time:\n prev_segment.extend(segment)\n else:\n prev_segment.append(segment[0])\n result_segments.append(prev_segment)\n prev_segment = segment\n if prev_segment is not None:\n result_segments.append(prev_segment)\n\n return result_segments" ]
[ 0.846430778503418, 0.7215781211853027, 0.7195752263069153, 0.685760498046875, 0.6824662089347839, 0.6763722896575928, 0.6726657152175903, 0.6619572043418884, 0.6599618792533875, 0.6594784259796143, 0.6542990803718567, 0.6521185040473938 ]
Return values (intensities) by indexes. Used for multiscale graph cut. data = [[0 1 1], [0 2 2], [0 2 2]] inds = [[0 1 2], [3 4 4], [5 4 4]] return: [0, 1, 1, 0, 2, 0] If the data are not consistent, it will take the maximal value
def __ordered_values_by_indexes(self, data, inds): """ Return values (intensities) by indexes. Used for multiscale graph cut. data = [[0 1 1], [0 2 2], [0 2 2]] inds = [[0 1 2], [3 4 4], [5 4 4]] return: [0, 1, 1, 0, 2, 0] If the data are not consistent, it will take the maximal value """ # get unique labels and their first indexes # lab, linds = np.unique(inds, return_index=True) # compute values by indexes # values = data.reshape(-1)[linds] # alternative slow implementation # if there are different data on same index, it will take # maximal value # lab = np.unique(inds) # values = [0]*len(lab) # for label in lab: # values[label] = np.max(data[inds == label]) # # values = np.asarray(values) # yet another implementation values = [None] * (np.max(inds) + 1) linear_inds = inds.ravel() linear_data = data.ravel() for i in range(0, len(linear_inds)): # going over all data pixels if values[linear_inds[i]] is None: # this index is found for first values[linear_inds[i]] = linear_data[i] elif values[linear_inds[i]] < linear_data[i]: # here can be changed maximal or minimal value values[linear_inds[i]] = linear_data[i] values = np.asarray(values) return values
[ "def get_maximum_index(indices):\n \"\"\"Internally used.\"\"\"\n def _maximum_idx_single(idx):\n if isinstance(idx, slice):\n start = -1\n stop = 0\n if idx.start is not None:\n start = idx.start.__index__()\n if idx.stop is not None:\n stop = idx.stop.__index__()\n return max(start, stop - 1)\n else:\n return idx.__index__()\n if isinstance(indices, tuple):\n return max((_maximum_idx_single(i) for i in indices), default=-1)\n else:\n return _maximum_idx_single(indices)", "def _get_indices(values, selected, tolerance):\n \"\"\"Get indices based on user-selected values.\n\n Parameters\n ----------\n values : ndarray (any dtype)\n values present in the axis.\n selected : ndarray (any dtype) or tuple or list\n values selected by the user\n tolerance : float\n avoid rounding errors.\n\n Returns\n -------\n idx_data : list of int\n indices of row/column to select the data\n idx_output : list of int\n indices of row/column to copy into output\n\n Notes\n -----\n This function is probably not very fast, but it's pretty robust. It keeps\n the order, which is extremely important.\n\n If you use values in the self.axis, you don't need to specify tolerance.\n However, if you specify arbitrary points, floating point errors might\n affect the actual values. Of course, using tolerance is much slower.\n\n Maybe tolerance should be part of Select instead of here.\n\n \"\"\"\n idx_data = []\n idx_output = []\n for idx_of_selected, one_selected in enumerate(selected):\n\n if tolerance is None or values.dtype.kind == 'U':\n idx_of_data = where(values == one_selected)[0]\n else:\n idx_of_data = where(abs(values - one_selected) <= tolerance)[0] # actual use min\n\n if len(idx_of_data) > 0:\n idx_data.append(idx_of_data[0])\n idx_output.append(idx_of_selected)\n\n return idx_data, idx_output", "def _slice_idxs(df, twin=None):\n \"\"\"\n Returns a slice of the incoming array filtered between\n the two times specified. Assumes the array is the same\n length as self.data. Acts in the time() and trace() functions.\n \"\"\"\n if twin is None:\n return 0, df.shape[0]\n\n tme = df.index\n\n if twin[0] is None:\n st_idx = 0\n else:\n st_idx = (np.abs(tme - twin[0])).argmin()\n if twin[1] is None:\n en_idx = df.shape[0]\n else:\n en_idx = (np.abs(tme - twin[1])).argmin() + 1\n return st_idx, en_idx", "def broadcast_indices(x, minv, ndim, axis):\n \"\"\"Calculate index values to properly broadcast index array within data array.\n\n See usage in interp.\n \"\"\"\n ret = []\n for dim in range(ndim):\n if dim == axis:\n ret.append(minv)\n else:\n broadcast_slice = [np.newaxis] * ndim\n broadcast_slice[dim] = slice(None)\n dim_inds = np.arange(x.shape[dim])\n ret.append(dim_inds[tuple(broadcast_slice)])\n return tuple(ret)", "def get_all_indices(self, n_samples=None, max_samples=None,\n random_state=None):\n \"\"\"Get the indices on which to evaluate the fitness of a program.\n\n Parameters\n ----------\n n_samples : int\n The number of samples.\n\n max_samples : int\n The maximum number of samples to use.\n\n random_state : RandomState instance\n The random number generator.\n\n Returns\n -------\n indices : array-like, shape = [n_samples]\n The in-sample indices.\n\n not_indices : array-like, shape = [n_samples]\n The out-of-sample indices.\n\n \"\"\"\n if self._indices_state is None and random_state is None:\n raise ValueError('The program has not been evaluated for fitness '\n 'yet, indices not available.')\n\n if n_samples is not None and self._n_samples is None:\n self._n_samples = n_samples\n if max_samples is not None and self._max_samples is None:\n self._max_samples = max_samples\n if random_state is not None and self._indices_state is None:\n self._indices_state = random_state.get_state()\n\n indices_state = check_random_state(None)\n indices_state.set_state(self._indices_state)\n\n not_indices = sample_without_replacement(\n self._n_samples,\n self._n_samples - self._max_samples,\n random_state=indices_state)\n sample_counts = np.bincount(not_indices, minlength=self._n_samples)\n indices = np.where(sample_counts == 0)[0]\n\n return indices, not_indices", "def select_data(self, iteration_indices):\n \"\"\"keep only data of `iteration_indices`\"\"\"\n dat = self\n iteridx = iteration_indices\n dat.f = dat.f[np.where([x in iteridx for x in dat.f[:, 0]])[0], :]\n dat.D = dat.D[np.where([x in iteridx for x in dat.D[:, 0]])[0], :]\n try:\n iteridx = list(iteridx)\n iteridx.append(iteridx[-1]) # last entry is artificial\n except:\n pass\n dat.std = dat.std[np.where([x in iteridx\n for x in dat.std[:, 0]])[0], :]\n dat.xmean = dat.xmean[np.where([x in iteridx\n for x in dat.xmean[:, 0]])[0], :]\n try:\n dat.xrecent = dat.x[np.where([x in iteridx for x in\n dat.xrecent[:, 0]])[0], :]\n except AttributeError:\n pass\n try:\n dat.corrspec = dat.x[np.where([x in iteridx for x in\n dat.corrspec[:, 0]])[0], :]\n except AttributeError:\n pass", "def get_highest_values(self, count):\n \"\"\"Get a list of the the x highest values of the Data Collection and their indices.\n\n This is useful for situations where one needs to know the times of\n the year when the largest values of a data collection occur. For example,\n there is a European dayight code that requires an analysis for the hours\n of the year with the greatest exterior illuminance level. This method\n can be used to help build a shcedule for such a study.\n\n Args:\n count: Integer representing the number of highest values to account for.\n\n Returns:\n highest_values: The n highest values in data list, ordered from\n highest to lowest.\n highest_values_index: Indicies of the n highest values in data\n list, ordered from highest to lowest.\n \"\"\"\n count = int(count)\n assert count <= len(self._values), \\\n 'count must be smaller than or equal to values length. {} > {}.'.format(\n count, len(self._values))\n assert count > 0, \\\n 'count must be greater than 0. Got {}.'.format(count)\n highest_values = sorted(self._values, reverse=True)[0:count]\n highest_values_index = sorted(list(xrange(len(self._values))),\n key=lambda k: self._values[k],\n reverse=True)[0:count]\n return highest_values, highest_values_index", "def create_index_tuple(group_ids):\n \"\"\"An helper function to create index tuples for fast lookup in HDF5Pump\"\"\"\n max_group_id = np.max(group_ids)\n\n start_idx_arr = np.full(max_group_id + 1, 0)\n n_items_arr = np.full(max_group_id + 1, 0)\n\n current_group_id = group_ids[0]\n current_idx = 0\n item_count = 0\n\n for group_id in group_ids:\n if group_id != current_group_id:\n start_idx_arr[current_group_id] = current_idx\n n_items_arr[current_group_id] = item_count\n current_idx += item_count\n item_count = 0\n current_group_id = group_id\n item_count += 1\n else:\n start_idx_arr[current_group_id] = current_idx\n n_items_arr[current_group_id] = item_count\n\n return (start_idx_arr, n_items_arr)", "def get_cutoff_indices(flow, fhigh, df, N):\n \"\"\"\n Gets the indices of a frequency series at which to stop an overlap\n calculation.\n\n Parameters\n ----------\n flow: float\n The frequency (in Hz) of the lower index.\n fhigh: float\n The frequency (in Hz) of the upper index.\n df: float\n The frequency step (in Hz) of the frequency series.\n N: int\n The number of points in the **time** series. Can be odd\n or even.\n\n Returns\n -------\n kmin: int\n kmax: int\n \"\"\"\n if flow:\n kmin = int(flow / df)\n if kmin < 0:\n err_msg = \"Start frequency cannot be negative. \"\n err_msg += \"Supplied value and kmin {} and {}\".format(flow, kmin)\n raise ValueError(err_msg)\n else:\n kmin = 1\n if fhigh:\n kmax = int(fhigh / df )\n if kmax > int((N + 1)/2.):\n kmax = int((N + 1)/2.)\n else:\n # int() truncates towards 0, so this is\n # equivalent to the floor of the float\n kmax = int((N + 1)/2.)\n\n if kmax <= kmin:\n err_msg = \"Kmax cannot be less than or equal to kmin. \"\n err_msg += \"Provided values of freqencies (min,max) were \"\n err_msg += \"{} and {} \".format(flow, fhigh)\n err_msg += \"corresponding to (kmin, kmax) of \"\n err_msg += \"{} and {}.\".format(kmin, kmax)\n raise ValueError(err_msg)\n\n return kmin,kmax", "def get_idx_rect(index_list):\r\n \"\"\"Extract the boundaries from a list of indexes\"\"\"\r\n rows, cols = list(zip(*[(i.row(), i.column()) for i in index_list]))\r\n return ( min(rows), max(rows), min(cols), max(cols) )", "def find_peaks_indexes(arr, window_width=5, threshold=0.0, fpeak=0):\n \"\"\"Find indexes of peaks in a 1d array.\n\n Note that window_width must be an odd number. The function imposes that the\n fluxes in the window_width /2 points to the left (and right) of the peak\n decrease monotonously as one moves away from the peak, except that\n it allows fpeak constant values around the peak.\n\n Parameters\n ----------\n arr : 1d numpy array\n Input 1D spectrum.\n window_width : int\n Width of the window where the peak must be found. This number must be\n odd.\n threshold : float\n Minimum signal in the peak (optional).\n fpeak: int\n Number of equal values around the peak\n\n Returns\n -------\n ipeaks : 1d numpy array (int)\n Indices of the input array arr in which the peaks have been found.\n\n\n \"\"\"\n\n _check_window_width(window_width)\n\n if (fpeak<0 or fpeak + 1 >= window_width):\n raise ValueError('fpeak must be in the range 0- window_width - 2')\n\n kernel_peak = kernel_peak_function(threshold, fpeak)\n out = generic_filter(arr, kernel_peak, window_width, mode=\"reflect\")\n result, = numpy.nonzero(out)\n\n return filter_array_margins(arr, result, window_width)", "def _validI(x, y, weights):\r\n '''\r\n return indices that have enough data points and are not erroneous \r\n '''\r\n # density filter:\r\n i = np.logical_and(np.isfinite(y), weights > np.median(weights))\r\n # filter outliers:\r\n try:\r\n grad = np.abs(np.gradient(y[i]))\r\n max_gradient = 4 * np.median(grad)\r\n i[i][grad > max_gradient] = False\r\n except (IndexError, ValueError):\r\n pass\r\n return i" ]
[ 0.7258252501487732, 0.7097887396812439, 0.7016910314559937, 0.7010431885719299, 0.6889966130256653, 0.6820541024208069, 0.678980827331543, 0.6788231134414673, 0.676472544670105, 0.6743552684783936, 0.6736085414886475, 0.672756016254425 ]
Function computes multiscale indexes of ndarray. mask: Says where is original resolution (0) and where is small resolution (1). Mask is in small resolution. orig_shape: Original shape of input data. zoom: Usually number greater then 1 result = [[0 1 2], [3 4 4], [5 4 4]]
def __hi2lo_multiscale_indexes(self, mask, orig_shape): # , zoom): """ Function computes multiscale indexes of ndarray. mask: Says where is original resolution (0) and where is small resolution (1). Mask is in small resolution. orig_shape: Original shape of input data. zoom: Usually number greater then 1 result = [[0 1 2], [3 4 4], [5 4 4]] """ mask_orig = zoom_to_shape(mask, orig_shape, dtype=np.int8) inds_small = np.arange(mask.size).reshape(mask.shape) inds_small_in_orig = zoom_to_shape(inds_small, orig_shape, dtype=np.int8) inds_orig = np.arange(np.prod(orig_shape)).reshape(orig_shape) # inds_orig = inds_orig * mask_orig inds_orig += np.max(inds_small_in_orig) + 1 # print 'indexes' # import py3DSeedEditor as ped # import pdb; pdb.set_trace() # BREAKPOINT # '==' is not the same as 'is' for numpy.array inds_small_in_orig[mask_orig == True] = inds_orig[mask_orig == True] # noqa inds = inds_small_in_orig # print np.max(inds) # print np.min(inds) inds = relabel_squeeze(inds) logger.debug( "Index after relabeling: %s", scipy.stats.describe(inds, axis=None) ) # logger.debug("Minimal index after relabeling: " + str(np.min(inds))) # inds_orig[mask_orig==True] = 0 # inds_small_in_orig[mask_orig==False] = 0 # inds = (inds_orig + np.max(inds_small_in_orig) + 1) + inds_small_in_orig return inds, mask_orig
[ "def construct_zernike_polynomials(x, y, zernike_indexes, mask=None, weight=None):\n \"\"\"Return the zerike polynomials for all objects in an image\n \n x - the X distance of a point from the center of its object\n y - the Y distance of a point from the center of its object\n zernike_indexes - an Nx2 array of the Zernike polynomials to be computed.\n mask - a mask with same shape as X and Y of the points to consider\n weight - weightings of points with the same shape as X and Y (default\n weight on each point is 1).\n \n returns a height x width x N array of complex numbers which are the\n e^i portion of the sine and cosine of the Zernikes\n \"\"\"\n if x.shape != y.shape:\n raise ValueError(\"X and Y must have the same shape\")\n if mask is None:\n pass\n elif mask.shape != x.shape:\n raise ValueError(\"The mask must have the same shape as X and Y\")\n else:\n x = x[mask]\n y = y[mask]\n if weight is not None:\n weight = weight[mask]\n lut = construct_zernike_lookuptable(zernike_indexes) # precompute poly. coeffs.\n nzernikes = zernike_indexes.shape[0]\n # compute radii\n r_square = np.square(x) # r_square = x**2\n np.add(r_square, np.square(y), out=r_square) # r_square = x**2 + y**2\n # z = y + 1j*x\n # each Zernike polynomial is poly(r)*(r**m * np.exp(1j*m*phi)) ==\n # poly(r)*(y + 1j*x)**m\n z = np.empty(x.shape, np.complex)\n np.copyto(z.real, y)\n np.copyto(z.imag, x)\n # preallocate buffers\n s = np.empty_like(x)\n zf = np.zeros((nzernikes,) + x.shape, np.complex)\n z_pows = {}\n for idx, (n, m) in enumerate(zernike_indexes):\n s[:]=0\n if not m in z_pows:\n if m == 0:\n z_pows[m] = np.complex(1.0)\n else:\n z_pows[m] = z if m == 1 else (z ** m)\n z_pow = z_pows[m]\n # use Horner scheme\n for k in range((n-m)//2+1):\n s *= r_square\n s += lut[idx, k]\n s[r_square>1]=0\n if weight is not None:\n s *= weight.astype(s.dtype)\n if m == 0:\n np.copyto(zf[idx], s) # zf[idx] = s\n else:\n np.multiply(s, z_pow, out=zf[idx]) # zf[idx] = s*exp_term\n \n if mask is None:\n result = zf.transpose( tuple(range(1, 1+x.ndim)) + (0, ))\n else:\n result = np.zeros( mask.shape + (nzernikes,), np.complex)\n result[mask] = zf.transpose( tuple(range(1, 1 + x.ndim)) + (0, ))\n return result", "def offset_mask(mask):\n \"\"\" Returns a mask shrunk to the 'minimum bounding rectangle' of the\n nonzero portion of the previous mask, and its offset from the original.\n Useful to find the smallest rectangular section of the image that can be\n extracted to include the entire geometry. Conforms to the y-first\n expectations of numpy arrays rather than x-first (geodata).\n \"\"\"\n def axis_data(axis):\n \"\"\"Gets the bounds of a masked area along a certain axis\"\"\"\n x = mask.sum(axis)\n trimmed_front = N.trim_zeros(x,\"f\")\n offset = len(x)-len(trimmed_front)\n size = len(N.trim_zeros(trimmed_front,\"b\"))\n return offset,size\n\n xo,xs = axis_data(0)\n yo,ys = axis_data(1)\n\n array = mask[yo:yo+ys,xo:xo+xs]\n offset = (yo,xo)\n return offset, array", "def scale(mask, mag_scale, outfile=None):\n \"\"\"\n Scale the completeness depth of a mask such that mag_new = mag + mag_scale.\n Input is a full HEALPix map.\n Optionally write out the scaled mask as an sparse HEALPix map.\n \"\"\"\n msg = \"'mask.scale': ADW 2018-05-05\"\n DeprecationWarning(msg)\n mask_new = hp.UNSEEN * np.ones(len(mask))\n mask_new[mask == 0.] = 0.\n mask_new[mask > 0.] = mask[mask > 0.] + mag_scale\n\n if outfile is not None:\n pix = np.nonzero(mask_new > 0.)[0]\n data_dict = {'MAGLIM': mask_new[pix]}\n nside = hp.npix2nside(len(mask_new))\n ugali.utils.skymap.writeSparseHealpixMap(pix, data_dict, nside, outfile)\n\n return mask_new", "def _compute_zs_mat(sz:TensorImageSize, scale:float, squish:float,\n invert:bool, row_pct:float, col_pct:float)->AffineMatrix:\n \"Utility routine to compute zoom/squish matrix.\"\n orig_ratio = math.sqrt(sz[1]/sz[0])\n for s,r,i in zip(scale,squish, invert):\n s,r = 1/math.sqrt(s),math.sqrt(r)\n if s * r <= 1 and s / r <= 1: #Test if we are completely inside the picture\n w,h = (s/r, s*r) if i else (s*r,s/r)\n col_c = (1-w) * (2*col_pct - 1)\n row_c = (1-h) * (2*row_pct - 1)\n return _get_zoom_mat(w, h, col_c, row_c)\n\n #Fallback, hack to emulate a center crop without cropping anything yet.\n if orig_ratio > 1: return _get_zoom_mat(1/orig_ratio**2, 1, 0, 0.)\n else: return _get_zoom_mat(1, orig_ratio**2, 0, 0.)", "def _findindex(az0, el0, az, el):\n \"\"\"\n inputs:\n ------\n az0, el0: N-D array of azimuth, elevation. May be masked arrays\n az, el: 1-D vectors of azimuth, elevation points from other camera to find closest angle for joint FOV.\n\n output:\n row, col: index of camera 0 closest to camera 1 FOV for each unmasked pixel\n\n I think with some minor tweaks this could be numba.jit if too slow.\n \"\"\"\n\n assert az0.size == el0.size # just for clarity\n assert az.ndim == el.ndim == 1, 'expect vector of test points'\n ic = np.empty(az.size, dtype=int)\n\n for i, (a, e) in enumerate(zip(az, el)):\n # we do this point by point because we need to know the closest pixel for each point\n # errang = haver.anglesep(az,el, apt,ept, deg=False)\n ic[i] = haver.anglesep_meeus(az0, el0, a, e, deg=False).argmin()\n\n \"\"\"\n THIS UNRAVEL_INDEX MUST BE ORDER = 'C'\n \"\"\"\n r, c = np.unravel_index(ic, az0.shape, order='C')\n\n mask = (c == 0) | (c == az0.shape[1] - 1) | (r == 0) | (r == az0.shape[0] - 1)\n\n r = np.ma.masked_where(mask, r)\n c = np.ma.masked_where(mask, c)\n\n return r, c", "def _makemasks(self, index=None, level=0):\n \"\"\"\n Internal function for generating masks for selecting values based on multi-index values.\n\n As all other multi-index functions will call this function, basic type-checking is also\n performed at this stage.\n \"\"\"\n if index is None:\n index = self.index\n\n try:\n dims = len(array(index).shape)\n if dims == 1:\n index = array(index, ndmin=2).T\n except:\n raise TypeError('A multi-index must be convertible to a numpy ndarray')\n\n try:\n index = index[:, level]\n except:\n raise ValueError(\"Levels must be indices into individual elements of the index\")\n\n lenIdx = index.shape[0]\n nlevels = index.shape[1]\n\n combs = product(*[unique(index.T[i, :]) for i in range(nlevels)])\n combs = array([l for l in combs])\n\n masks = array([[array_equal(index[i], c) for i in range(lenIdx)] for c in combs])\n\n return zip(*[(masks[x], combs[x]) for x in range(len(masks)) if masks[x].any()])", "def seed_zoom(seeds, zoom):\n \"\"\"\n Smart zoom for sparse matrix. If there is resize to bigger resolution\n thin line of label could be lost. This function prefers labels larger\n then zero. If there is only one small voxel in larger volume with zeros\n it is selected.\n \"\"\"\n # import scipy\n # loseeds=seeds\n labels = np.unique(seeds)\n # remove first label - 0\n labels = np.delete(labels, 0)\n # @TODO smart interpolation for seeds in one block\n # loseeds = scipy.ndimage.interpolation.zoom(\n # seeds, zoom, order=0)\n loshape = np.ceil(np.array(seeds.shape) * 1.0 / zoom).astype(np.int)\n loseeds = np.zeros(loshape, dtype=np.int8)\n loseeds = loseeds.astype(np.int8)\n for label in labels:\n a, b, c = np.where(seeds == label)\n loa = np.round(a // zoom)\n lob = np.round(b // zoom)\n loc = np.round(c // zoom)\n # loseeds = np.zeros(loshape)\n\n loseeds[loa, lob, loc] += label\n # this is to detect conflict seeds\n loseeds[loseeds > label] = 100\n\n # remove conflict seeds\n loseeds[loseeds > 99] = 0\n\n # import py3DSeedEditor\n # ped = py3DSeedEditor.py3DSeedEditor(loseeds)\n # ped.show()\n\n return loseeds", "def get_mask(cls, azim):\n \"\"\"Linear interpolation between two points of the mask\n \"\"\"\n\n if cls.mask is None:\n raise ValueError(\"No mask defined for the station {}\".format(cls.name))\n\n azim %= 2 * np.pi\n\n if azim in cls.mask[0, :]:\n return cls.mask[1, np.where(azim == cls.mask[0, :])[0][0]]\n\n for next_i, mask_azim in enumerate(cls.mask[0, :]):\n if mask_azim > azim:\n break\n else:\n next_i = 0\n\n x0, y0 = cls.mask[:, next_i - 1]\n x1, y1 = cls.mask[:, next_i]\n\n if next_i - 1 == -1:\n x0 = 0\n\n return y0 + (y1 - y0) * (azim - x0) / (x1 - x0)", "def _scale_shape(dshape, scale = (1,1,1)):\n \"\"\"returns the shape after scaling (should be the same as ndimage.zoom\"\"\"\n nshape = np.round(np.array(dshape) * np.array(scale))\n return tuple(nshape.astype(np.int))", "def cuts_from_bbox(mask_nii, cuts=3):\n \"\"\"Finds equi-spaced cuts for presenting images\"\"\"\n from nibabel.affines import apply_affine\n\n mask_data = mask_nii.get_data() > 0.0\n\n # First, project the number of masked voxels on each axes\n ijk_counts = [\n mask_data.sum(2).sum(1), # project sagittal planes to transverse (i) axis\n mask_data.sum(2).sum(0), # project coronal planes to to longitudinal (j) axis\n mask_data.sum(1).sum(0), # project axial planes to vertical (k) axis\n ]\n\n # If all voxels are masked in a slice (say that happens at k=10),\n # then the value for ijk_counts for the projection to k (ie. ijk_counts[2])\n # at that element of the orthogonal axes (ijk_counts[2][10]) is\n # the total number of voxels in that slice (ie. Ni x Nj).\n # Here we define some thresholds to consider the plane as \"masked\"\n # The thresholds vary because of the shape of the brain\n # I have manually found that for the axial view requiring 30%\n # of the slice elements to be masked drops almost empty boxes\n # in the mosaic of axial planes (and also addresses #281)\n ijk_th = [\n int((mask_data.shape[1] * mask_data.shape[2]) * 0.2), # sagittal\n int((mask_data.shape[0] * mask_data.shape[2]) * 0.0), # coronal\n int((mask_data.shape[0] * mask_data.shape[1]) * 0.3), # axial\n ]\n\n vox_coords = []\n for ax, (c, th) in enumerate(zip(ijk_counts, ijk_th)):\n B = np.argwhere(c > th)\n if B.size:\n smin, smax = B.min(), B.max()\n\n # Avoid too narrow selections of cuts (very small masks)\n if not B.size or (th > 0 and (smin + cuts + 1) >= smax):\n B = np.argwhere(c > 0)\n\n # Resort to full plane if mask is seemingly empty\n smin, smax = B.min(), B.max() if B.size else (0, mask_data.shape[ax])\n inc = (smax - smin) / (cuts + 1)\n vox_coords.append([smin + (i + 1) * inc for i in range(cuts)])\n\n ras_coords = []\n for cross in np.array(vox_coords).T:\n ras_coords.append(apply_affine(\n mask_nii.affine, cross).tolist())\n ras_cuts = [list(coords) for coords in np.transpose(ras_coords)]\n return {k: v for k, v in zip(['x', 'y', 'z'], ras_cuts)}", "def _crop_data(self):\n \"\"\"\n Crop the ``data`` and ``mask`` to have an integer number of\n background meshes of size ``box_size`` in both dimensions. The\n data are cropped on the top and/or right edges (this is the best\n option for the \"zoom\" interpolator).\n\n Returns\n -------\n result : `~numpy.ma.MaskedArray`\n The cropped data and mask as a masked array.\n \"\"\"\n\n ny_crop = self.nyboxes * self.box_size[1]\n nx_crop = self.nxboxes * self.box_size[0]\n crop_slc = index_exp[0:ny_crop, 0:nx_crop]\n if self.mask is not None:\n mask = self.mask[crop_slc]\n else:\n mask = False\n\n return np.ma.masked_array(self.data[crop_slc], mask=mask)", "def calculate_origin_and_size(canvas_size, data_shape, image_canvas_mode, image_zoom, image_position) -> typing.Tuple[typing.Any, typing.Any]:\n \"\"\"Calculate origin and size for canvas size, data shape, and image display parameters.\"\"\"\n if data_shape is None:\n return None, None\n if image_canvas_mode == \"fill\":\n data_shape = data_shape\n scale_h = float(data_shape[1]) / canvas_size[1]\n scale_v = float(data_shape[0]) / canvas_size[0]\n if scale_v < scale_h:\n image_canvas_size = (canvas_size[0], canvas_size[0] * data_shape[1] / data_shape[0])\n else:\n image_canvas_size = (canvas_size[1] * data_shape[0] / data_shape[1], canvas_size[1])\n 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)\n elif image_canvas_mode == \"fit\":\n image_canvas_size = canvas_size\n image_canvas_origin = (0, 0)\n elif image_canvas_mode == \"1:1\":\n image_canvas_size = data_shape\n 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)\n elif image_canvas_mode == \"2:1\":\n image_canvas_size = (data_shape[0] * 0.5, data_shape[1] * 0.5)\n 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)\n else:\n image_canvas_size = (canvas_size[0] * image_zoom, canvas_size[1] * image_zoom)\n canvas_rect = Geometry.fit_to_size(((0, 0), image_canvas_size), data_shape)\n image_canvas_origin_y = (canvas_size[0] * 0.5) - image_position[0] * canvas_rect[1][0] - canvas_rect[0][0]\n image_canvas_origin_x = (canvas_size[1] * 0.5) - image_position[1] * canvas_rect[1][1] - canvas_rect[0][1]\n image_canvas_origin = (image_canvas_origin_y, image_canvas_origin_x)\n return image_canvas_origin, image_canvas_size" ]
[ 0.6771979928016663, 0.6765623092651367, 0.6748027205467224, 0.6736266016960144, 0.6680997014045715, 0.6649146676063538, 0.6602632999420166, 0.6561344265937805, 0.65461266040802, 0.6545136570930481, 0.6541271209716797, 0.6522963047027588 ]
Interactive seed setting with 3d seed editor
def interactivity(self, min_val=None, max_val=None, qt_app=None): """ Interactive seed setting with 3d seed editor """ from .seed_editor_qt import QTSeedEditor from PyQt4.QtGui import QApplication if min_val is None: min_val = np.min(self.img) if max_val is None: max_val = np.max(self.img) window_c = (max_val + min_val) / 2 # .astype(np.int16) window_w = max_val - min_val # .astype(np.int16) if qt_app is None: qt_app = QApplication(sys.argv) pyed = QTSeedEditor( self.img, modeFun=self.interactivity_loop, voxelSize=self.voxelsize, seeds=self.seeds, volume_unit=self.volume_unit, ) pyed.changeC(window_c) pyed.changeW(window_w) qt_app.exec_()
[ "def set_seed(seed: int):\n \"\"\" Set random seed for python, numpy and pytorch RNGs \"\"\"\n random.seed(seed)\n np.random.seed(seed)\n torch.random.manual_seed(seed)", "def set_seeds(self, seeds):\n \"\"\"\n Function for manual seed setting. Sets variable seeds and prepares\n voxels for density model.\n :param seeds: ndarray (0 - nothing, 1 - object, 2 - background,\n 3 - object just hard constraints, no model training, 4 - background \n just hard constraints, no model training)\n \"\"\"\n if self.img.shape != seeds.shape:\n raise Exception(\"Seeds must be same size as input image\")\n\n self.seeds = seeds.astype(\"int8\")\n self.voxels1 = self.img[self.seeds == 1]\n self.voxels2 = self.img[self.seeds == 2]", "function autoseed(seed) {\n try {\n global.crypto.getRandomValues(seed = new Uint8Array(width));\n return tostring(seed);\n } catch (e) {\n return [+new Date, global, global.navigator.plugins,\n global.screen, tostring(pool)];\n }\n}", "function Seeder(knex) {\n this.knex = knex;\n this.config = this.setConfig(knex.client.config.seeds);\n}", "def fetchExternalUpdates(self):\r\n \"\"\"\r\n !Experimental!\r\n Calls out to the client code requesting seed values to use in the UI\r\n !Experimental!\r\n \"\"\"\r\n seeds = seeder.fetchDynamicProperties(\r\n self.buildSpec['target'],\r\n self.buildSpec['encoding']\r\n )\r\n for config in self.configs:\r\n config.seedUI(seeds)", "def set_seed(self, rho_seed, mu_seed):\n\n \"\"\"\n set seeds manually (should add dimensionality check)\n \"\"\"\n\n self.rho = rho_seed\n self.mu = mu_seed", "def _set_seed(self):\n \"\"\" Set random seed for numpy and tensorflow packages \"\"\"\n if self.flags['SEED'] is not None:\n tf.set_random_seed(self.flags['SEED'])\n np.random.seed(self.flags['SEED'])", "def set_state(seed_value=None, step=None):\n \"\"\"Set random seed.\"\"\"\n global RANDOM_SEED # pylint: disable=global-statement\n if seed_value is not None:\n RANDOM_SEED = seed_value\n if step is not None:\n RANDOM_SEED += step", "def seed(self):\n \"\"\" Reset the number from which the next generated sequence start.\n If you seed at 100, next seed will be 101\n \"\"\"\n form = self.request.form\n prefix = form.get('prefix', None)\n if prefix is None:\n return 'No prefix provided'\n seed = form.get('seed', None)\n if seed is None:\n return 'No seed provided'\n if not seed.isdigit():\n return 'Seed must be a digit'\n seed = int(seed)\n if seed < 0:\n return 'Seed cannot be negative'\n\n new_seq = self.set_seed(prefix, seed)\n return 'IDServerView: \"%s\" seeded to %s' % (prefix, new_seq)", "private function seed()\n {\n $action = $this->arg->getParameter('action');\n\n if (!in_array($action, ['all', 'table'])) {\n $this->throwFailsCommand('This action is not exists', 'help seed');\n }\n\n if ($action == 'all') {\n if ($this->arg->getParameter('target') != null) {\n $this->throwFailsAction('Bad command usage', 'help seed');\n }\n }\n\n // Set command for understand\n $command = $action;\n\n $this->command->call(\n $command,\n 'seeder',\n $this->arg->getParameter('target')\n );\n }", "def check_manual_seed(seed):\n \"\"\" If manual seed is not specified, choose a random one and communicate it to the user.\n\n \"\"\"\n\n seed = seed or random.randint(1, 10000)\n random.seed(seed)\n torch.manual_seed(seed)\n\n print('Using manual seed: {seed}'.format(seed=seed))", "def setSeed(self, value):\n \"\"\"\n Sets the seed to value.\n \"\"\"\n self.seed = value\n random.seed(self.seed)\n if self.verbosity >= 0:\n print(\"Conx using seed:\", self.seed)" ]
[ 0.7103196382522583, 0.7084529399871826, 0.7084075212478638, 0.7056494355201721, 0.6945380568504333, 0.6907649636268616, 0.6894176006317139, 0.6885712146759033, 0.6882632374763489, 0.6879781484603882, 0.6860505938529968, 0.6801682710647583 ]
Function for manual seed setting. Sets variable seeds and prepares voxels for density model. :param seeds: ndarray (0 - nothing, 1 - object, 2 - background, 3 - object just hard constraints, no model training, 4 - background just hard constraints, no model training)
def set_seeds(self, seeds): """ Function for manual seed setting. Sets variable seeds and prepares voxels for density model. :param seeds: ndarray (0 - nothing, 1 - object, 2 - background, 3 - object just hard constraints, no model training, 4 - background just hard constraints, no model training) """ if self.img.shape != seeds.shape: raise Exception("Seeds must be same size as input image") self.seeds = seeds.astype("int8") self.voxels1 = self.img[self.seeds == 1] self.voxels2 = self.img[self.seeds == 2]
[ "def __set_hard_hard_constraints(self, tdata1, tdata2, seeds):\n \"\"\"\n it works with seed labels:\n 0: nothing\n 1: object 1 - full seeds\n 2: object 2 - full seeds\n 3: object 1 - not a training seeds\n 4: object 2 - not a training seeds\n \"\"\"\n seeds_mask = (seeds == 1) | (seeds == 3)\n tdata2[seeds_mask] = np.max(tdata2) + 1\n tdata1[seeds_mask] = 0\n\n seeds_mask = (seeds == 2) | (seeds == 4)\n tdata1[seeds_mask] = np.max(tdata1) + 1\n tdata2[seeds_mask] = 0\n\n return tdata1, tdata2", "public void setWebSeeds(List<WebSeedEntry> seeds) {\n web_seed_entry_vector v = new web_seed_entry_vector();\n\n for (WebSeedEntry e : seeds) {\n v.push_back(e.swig());\n }\n\n ti.set_web_seeds(v);\n }", "def _set_seed(self):\n \"\"\" Set random seed for numpy and tensorflow packages \"\"\"\n if self.flags['SEED'] is not None:\n tf.set_random_seed(self.flags['SEED'])\n np.random.seed(self.flags['SEED'])", "def set_seed(self, rho_seed, mu_seed):\n\n \"\"\"\n set seeds manually (should add dimensionality check)\n \"\"\"\n\n self.rho = rho_seed\n self.mu = mu_seed", "def prepare_environment(params: Params):\n \"\"\"\n Sets random seeds for reproducible experiments. This may not work as expected\n if you use this from within a python project in which you have already imported Pytorch.\n If you use the scripts/run_model.py entry point to training models with this library,\n your experiments should be reasonably reproducible. If you are using this from your own\n project, you will want to call this function before importing Pytorch. Complete determinism\n is very difficult to achieve with libraries doing optimized linear algebra due to massively\n parallel execution, which is exacerbated by using GPUs.\n\n Parameters\n ----------\n params: Params object or dict, required.\n A ``Params`` object or dict holding the json parameters.\n \"\"\"\n seed = params.pop_int(\"random_seed\", 13370)\n numpy_seed = params.pop_int(\"numpy_seed\", 1337)\n torch_seed = params.pop_int(\"pytorch_seed\", 133)\n\n if seed is not None:\n random.seed(seed)\n if numpy_seed is not None:\n numpy.random.seed(numpy_seed)\n if torch_seed is not None:\n torch.manual_seed(torch_seed)\n # Seed all GPUs with the same seed if available.\n if torch.cuda.is_available():\n torch.cuda.manual_seed_all(torch_seed)\n\n log_pytorch_version_info()", "def set_seed(seed: int):\n \"\"\" Set random seed for python, numpy and pytorch RNGs \"\"\"\n random.seed(seed)\n np.random.seed(seed)\n torch.random.manual_seed(seed)", "def set_seed(self, seed):\n\n \"\"\"\n Override default values for random initial topic assignment,\n set to \"seed\" instead.\n seed is 2-d array (number of samples in LDA model x number\n of tokens in LDA model)\n \"\"\"\n\n assert seed.dtype == np.int and seed.shape == (self.samples, self.N)\n self.topic_seed = seed", "def seeds(args):\n \"\"\"\n %prog seeds [pngfile|jpgfile]\n\n Extract seed metrics from [pngfile|jpgfile]. Use --rows and --cols to crop image.\n \"\"\"\n p = OptionParser(seeds.__doc__)\n p.set_outfile()\n opts, args, iopts = add_seeds_options(p, args)\n\n if len(args) != 1:\n sys.exit(not p.print_help())\n\n pngfile, = args\n pf = opts.prefix or op.basename(pngfile).rsplit(\".\", 1)[0]\n sigma, kernel = opts.sigma, opts.kernel\n rows, cols = opts.rows, opts.cols\n labelrows, labelcols = opts.labelrows, opts.labelcols\n ff = opts.filter\n calib = opts.calibrate\n outdir = opts.outdir\n if outdir != '.':\n mkdir(outdir)\n if calib:\n calib = json.load(must_open(calib))\n pixel_cm_ratio, tr = calib[\"PixelCMratio\"], calib[\"RGBtransform\"]\n tr = np.array(tr)\n\n resizefile, mainfile, labelfile, exif = \\\n convert_image(pngfile, pf, outdir=outdir,\n rotate=opts.rotate,\n rows=rows, cols=cols,\n labelrows=labelrows, labelcols=labelcols)\n\n oimg = load_image(resizefile)\n img = load_image(mainfile)\n\n fig, (ax1, ax2, ax3, ax4) = plt.subplots(ncols=4, nrows=1,\n figsize=(iopts.w, iopts.h))\n\n # Edge detection\n img_gray = rgb2gray(img)\n logging.debug(\"Running {0} edge detection ...\".format(ff))\n if ff == \"canny\":\n edges = canny(img_gray, sigma=opts.sigma)\n elif ff == \"roberts\":\n edges = roberts(img_gray)\n elif ff == \"sobel\":\n edges = sobel(img_gray)\n edges = clear_border(edges, buffer_size=opts.border)\n selem = disk(kernel)\n closed = closing(edges, selem) if kernel else edges\n filled = binary_fill_holes(closed)\n\n # Watershed algorithm\n if opts.watershed:\n distance = distance_transform_edt(filled)\n local_maxi = peak_local_max(distance, threshold_rel=.05, indices=False)\n coordinates = peak_local_max(distance, threshold_rel=.05)\n markers, nmarkers = label(local_maxi, return_num=True)\n logging.debug(\"Identified {0} watershed markers\".format(nmarkers))\n labels = watershed(closed, markers, mask=filled)\n else:\n labels = label(filled)\n\n # Object size filtering\n w, h = img_gray.shape\n canvas_size = w * h\n min_size = int(round(canvas_size * opts.minsize / 100))\n max_size = int(round(canvas_size * opts.maxsize / 100))\n logging.debug(\"Find objects with pixels between {0} ({1}%) and {2} ({3}%)\"\\\n .format(min_size, opts.minsize, max_size, opts.maxsize))\n\n # Plotting\n ax1.set_title('Original picture')\n ax1.imshow(oimg)\n\n params = \"{0}, $\\sigma$={1}, $k$={2}\".format(ff, sigma, kernel)\n if opts.watershed:\n params += \", watershed\"\n ax2.set_title('Edge detection\\n({0})'.format(params))\n closed = gray2rgb(closed)\n ax2_img = labels\n if opts.edges:\n ax2_img = closed\n elif opts.watershed:\n ax2.plot(coordinates[:, 1], coordinates[:, 0], 'g.')\n ax2.imshow(ax2_img, cmap=iopts.cmap)\n\n ax3.set_title('Object detection')\n ax3.imshow(img)\n\n filename = op.basename(pngfile)\n if labelfile:\n accession = extract_label(labelfile)\n else:\n accession = pf\n\n # Calculate region properties\n rp = regionprops(labels)\n rp = [x for x in rp if min_size <= x.area <= max_size]\n nb_labels = len(rp)\n logging.debug(\"A total of {0} objects identified.\".format(nb_labels))\n objects = []\n for i, props in enumerate(rp):\n i += 1\n if i > opts.count:\n break\n\n y0, x0 = props.centroid\n orientation = props.orientation\n major, minor = props.major_axis_length, props.minor_axis_length\n major_dx = cos(orientation) * major / 2\n major_dy = sin(orientation) * major / 2\n minor_dx = sin(orientation) * minor / 2\n minor_dy = cos(orientation) * minor / 2\n ax2.plot((x0 - major_dx, x0 + major_dx),\n (y0 + major_dy, y0 - major_dy), 'r-')\n ax2.plot((x0 - minor_dx, x0 + minor_dx),\n (y0 - minor_dy, y0 + minor_dy), 'r-')\n\n npixels = int(props.area)\n # Sample the center of the blob for color\n d = min(int(round(minor / 2 * .35)) + 1, 50)\n x0d, y0d = int(round(x0)), int(round(y0))\n square = img[(y0d - d):(y0d + d), (x0d - d):(x0d + d)]\n pixels = []\n for row in square:\n pixels.extend(row)\n logging.debug(\"Seed #{0}: {1} pixels ({2} sampled) - {3:.2f}%\".\\\n format(i, npixels, len(pixels), 100. * npixels / canvas_size))\n\n rgb = pixel_stats(pixels)\n objects.append(Seed(filename, accession, i, rgb, props, exif))\n minr, minc, maxr, maxc = props.bbox\n rect = Rectangle((minc, minr), maxc - minc, maxr - minr,\n fill=False, ec='w', lw=1)\n ax3.add_patch(rect)\n mc, mr = (minc + maxc) / 2, (minr + maxr) / 2\n ax3.text(mc, mr, \"{0}\".format(i), color='w',\n ha=\"center\", va=\"center\", size=6)\n\n for ax in (ax2, ax3):\n ax.set_xlim(0, h)\n ax.set_ylim(w, 0)\n\n # Output identified seed stats\n ax4.text(.1, .92, \"File: {0}\".format(latex(filename)), color='g')\n ax4.text(.1, .86, \"Label: {0}\".format(latex(accession)), color='m')\n yy = .8\n fw = must_open(opts.outfile, \"w\")\n if not opts.noheader:\n print(Seed.header(calibrate=calib), file=fw)\n for o in objects:\n if calib:\n o.calibrate(pixel_cm_ratio, tr)\n print(o, file=fw)\n i = o.seedno\n if i > 7:\n continue\n ax4.text(.01, yy, str(i), va=\"center\", bbox=dict(fc='none', ec='k'))\n ax4.text(.1, yy, o.pixeltag, va=\"center\")\n yy -= .04\n ax4.add_patch(Rectangle((.1, yy - .025), .12, .05, lw=0,\n fc=rgb_to_hex(o.rgb)))\n ax4.text(.27, yy, o.hashtag, va=\"center\")\n yy -= .06\n ax4.text(.1 , yy, \"(A total of {0} objects displayed)\".format(nb_labels),\n color=\"darkslategrey\")\n normalize_axes(ax4)\n\n for ax in (ax1, ax2, ax3):\n xticklabels = [int(x) for x in ax.get_xticks()]\n yticklabels = [int(x) for x in ax.get_yticks()]\n ax.set_xticklabels(xticklabels, family='Helvetica', size=8)\n ax.set_yticklabels(yticklabels, family='Helvetica', size=8)\n\n image_name = op.join(outdir, pf + \".\" + iopts.format)\n savefig(image_name, dpi=iopts.dpi, iopts=iopts)\n return objects", "def _process_input_seed(seed_photon_fields):\n \"\"\"\n take input list of seed_photon_fields and fix them into usable format\n \"\"\"\n\n Tcmb = 2.72548 * u.K # 0.00057 K\n Tfir = 30 * u.K\n ufir = 0.5 * u.eV / u.cm ** 3\n Tnir = 3000 * u.K\n unir = 1.0 * u.eV / u.cm ** 3\n\n # Allow for seed_photon_fields definitions of the type 'CMB-NIR-FIR' or\n # 'CMB'\n if type(seed_photon_fields) != list:\n seed_photon_fields = seed_photon_fields.split(\"-\")\n\n result = OrderedDict()\n\n for idx, inseed in enumerate(seed_photon_fields):\n seed = {}\n if isinstance(inseed, six.string_types):\n name = inseed\n seed[\"type\"] = \"thermal\"\n if inseed == \"CMB\":\n seed[\"T\"] = Tcmb\n seed[\"u\"] = ar * Tcmb ** 4\n seed[\"isotropic\"] = True\n elif inseed == \"FIR\":\n seed[\"T\"] = Tfir\n seed[\"u\"] = ufir\n seed[\"isotropic\"] = True\n elif inseed == \"NIR\":\n seed[\"T\"] = Tnir\n seed[\"u\"] = unir\n seed[\"isotropic\"] = True\n else:\n log.warning(\n \"Will not use seed {0} because it is not \"\n \"CMB, FIR or NIR\".format(inseed)\n )\n raise TypeError\n elif type(inseed) == list and (\n len(inseed) == 3 or len(inseed) == 4\n ):\n isotropic = len(inseed) == 3\n\n if isotropic:\n name, T, uu = inseed\n seed[\"isotropic\"] = True\n else:\n name, T, uu, theta = inseed\n seed[\"isotropic\"] = False\n seed[\"theta\"] = validate_scalar(\n \"{0}-theta\".format(name), theta, physical_type=\"angle\"\n )\n\n thermal = T.unit.physical_type == \"temperature\"\n\n if thermal:\n seed[\"type\"] = \"thermal\"\n validate_scalar(\n \"{0}-T\".format(name),\n T,\n domain=\"positive\",\n physical_type=\"temperature\",\n )\n seed[\"T\"] = T\n if uu == 0:\n seed[\"u\"] = ar * T ** 4\n else:\n # pressure has same physical type as energy density\n validate_scalar(\n \"{0}-u\".format(name),\n uu,\n domain=\"positive\",\n physical_type=\"pressure\",\n )\n seed[\"u\"] = uu\n else:\n seed[\"type\"] = \"array\"\n # Ensure everything is in arrays\n T = u.Quantity((T,)).flatten()\n uu = u.Quantity((uu,)).flatten()\n\n seed[\"energy\"] = validate_array(\n \"{0}-energy\".format(name),\n T,\n domain=\"positive\",\n physical_type=\"energy\",\n )\n\n if np.isscalar(seed[\"energy\"]) or seed[\"energy\"].size == 1:\n seed[\"photon_density\"] = validate_scalar(\n \"{0}-density\".format(name),\n uu,\n domain=\"positive\",\n physical_type=\"pressure\",\n )\n else:\n if uu.unit.physical_type == \"pressure\":\n uu /= seed[\"energy\"] ** 2\n seed[\"photon_density\"] = validate_array(\n \"{0}-density\".format(name),\n uu,\n domain=\"positive\",\n physical_type=\"differential number density\",\n )\n else:\n raise TypeError(\n \"Unable to process seed photon\"\n \" field: {0}\".format(inseed)\n )\n\n result[name] = seed\n\n return result", "def set_parameters\n # Convert the volumes to vectors:\n @vectors = Array.new\n @volumes.each {|volume| @vectors << volume.flatten}\n verify_equal_vector_lengths\n # Number of voxels:\n @n = @vectors.first.length\n # Number of raters:\n @r = @vectors.length\n # Decisions array:\n @decisions = NArray.int(@n, @r)\n # Sensitivity vector: (Def: true positive fraction, or relative frequency of Dij = 1 when Ti = 1)\n # (If a rater includes all the voxels that are included in the true segmentation, his score is 1.0 on this parameter)\n @p = NArray.float(@r)\n # Specificity vector: (Def: true negative fraction, or relative frequency of Dij = 0 when Ti = 0)\n # (If a rater has avoided to specify any voxels that are not specified in the true segmentation, his score is 1.0 on this parameter)\n @q = NArray.float(@r)\n # Set initial parameter values: (p0, q0) - when combined, called: phi0\n @p.fill!(0.99999)\n @q.fill!(0.99999)\n # Combined scoring parameter:\n @phi = NArray.float(2, @r)\n # Fill the decisions matrix:\n @vectors.each_with_index do |decision, j|\n @decisions[true, j] = decision\n end\n # Indicator vector of the true (hidden) segmentation:\n @true_segmentation = NArray.byte(@n)\n # The estimate of the probability that the true segmentation at each voxel is Ti = 1: f(Ti=1)\n @weights_previous = NArray.float(@n)\n # Using the notation commom for EM algorithms and refering to this as the weight variable:\n @weights_current = NArray.float(@n)\n end", "def return_fv_by_seeds(fv, seeds=None, unique_cls=None):\n \"\"\"\n Return features selected by seeds and unique_cls or selection from features and corresponding seed classes.\n\n :param fv: ndarray with lineariezed feature. It's shape is MxN, where M is number of image pixels and N is number\n of features\n :param seeds: ndarray with seeds. Does not to be linear.\n :param unique_cls: number of used seeds clases. Like [1, 2]\n :return: fv, sd - selection from feature vector and selection from seeds or just fv for whole image\n \"\"\"\n if seeds is not None:\n if unique_cls is not None:\n return select_from_fv_by_seeds(fv, seeds, unique_cls)\n else:\n raise AssertionError(\"Input unique_cls has to be not None if seeds is not None.\")\n else:\n return fv", "def fit_from_image(self, data, voxelsize, seeds, unique_cls):\n \"\"\"\n This Method allows computes feature vector and train model.\n\n :cls: list of index number of requested classes in seeds\n \"\"\"\n fvs, clsselected = self.features_from_image(data, voxelsize, seeds, unique_cls)\n self.fit(fvs, clsselected)" ]
[ 0.724362850189209, 0.7048511505126953, 0.6971395015716553, 0.6954063177108765, 0.6898720860481262, 0.6891217231750488, 0.6812682151794434, 0.6777561902999878, 0.6749814748764038, 0.6689315438270569, 0.6673877835273743, 0.6638182401657104 ]
Run the Graph Cut segmentation according to preset parameters. :param run_fit_model: Allow to skip model fit when the model is prepared before :return:
def run(self, run_fit_model=True): """ Run the Graph Cut segmentation according to preset parameters. :param run_fit_model: Allow to skip model fit when the model is prepared before :return: """ if run_fit_model: self.fit_model(self.img, self.voxelsize, self.seeds) self._start_time = time.time() if self.segparams["method"].lower() in ("graphcut", "gc"): self.__single_scale_gc_run() elif self.segparams["method"].lower() in ( "multiscale_graphcut", "multiscale_gc", "msgc", "msgc_lo2hi", "lo2hi", "multiscale_graphcut_lo2hi", ): logger.debug("performing multiscale Graph-Cut lo2hi") self.__multiscale_gc_lo2hi_run() elif self.segparams["method"].lower() in ( "msgc_hi2lo", "hi2lo", "multiscale_graphcut_hi2lo", ): logger.debug("performing multiscale Graph-Cut hi2lo") self.__multiscale_gc_hi2lo_run() else: logger.error("Unknown segmentation method: " + self.segparams["method"])
[ "def model_segments(copy_file, work_dir, paired):\n \"\"\"Perform segmentation on input copy number log2 ratio file.\n \"\"\"\n out_file = os.path.join(work_dir, \"%s.cr.seg\" % dd.get_sample_name(paired.tumor_data))\n tumor_counts, normal_counts = heterogzygote_counts(paired)\n if not utils.file_exists(out_file):\n with file_transaction(paired.tumor_data, out_file) as tx_out_file:\n params = [\"-T\", \"ModelSegments\",\n \"--denoised-copy-ratios\", copy_file,\n \"--allelic-counts\", tumor_counts,\n \"--output-prefix\", dd.get_sample_name(paired.tumor_data),\n \"-O\", os.path.dirname(tx_out_file)]\n if normal_counts:\n params += [\"--normal-allelic-counts\", normal_counts]\n _run_with_memory_scaling(params, tx_out_file, paired.tumor_data)\n for tx_fname in glob.glob(os.path.join(os.path.dirname(tx_out_file),\n \"%s*\" % dd.get_sample_name(paired.tumor_data))):\n shutil.copy(tx_fname, os.path.join(work_dir, os.path.basename(tx_fname)))\n return {\"seg\": out_file, \"tumor_hets\": out_file.replace(\".cr.seg\", \".hets.tsv\"),\n \"final_seg\": out_file.replace(\".cr.seg\", \".modelFinal.seg\")}", "def run_model(self,\n op_list,\n num_steps,\n feed_vars=(),\n feed_data=None,\n print_every=100,\n allow_initialize=True):\n \"\"\"Runs `op_list` for `num_steps`.\n\n Args:\n op_list: A list of ops to run.\n num_steps: Number of steps to run this for. If feeds are used, this is a\n maximum. `None` can be used to signal \"forever\".\n feed_vars: The variables to feed.\n feed_data: An iterator that feeds data tuples.\n print_every: Print a log line and checkpoing every so many steps.\n allow_initialize: If True, the model will be initialized if any variable\n is uninitialized, if False the model will not be initialized.\n Returns:\n The final run result as a list.\n Raises:\n ValueError: If feed_data doesn't match feed_vars.\n \"\"\"\n feed_data = feed_data or itertools.repeat(())\n\n ops = [bookkeeper.global_step()]\n ops.extend(op_list)\n\n sess = tf.get_default_session()\n self.prepare_model(sess, allow_initialize=allow_initialize)\n results = []\n\n try:\n if num_steps is None:\n counter = itertools.count(0)\n elif num_steps >= 0:\n counter = xrange(num_steps)\n else:\n raise ValueError('num_steps cannot be negative: %s' % num_steps)\n for i, data in zip(counter, feed_data):\n log_this_time = print_every and i % print_every == 0\n if len(data) != len(feed_vars):\n raise ValueError(\n 'feed_data and feed_vars must be the same length: %d vs %d' % (\n len(data), len(feed_vars)))\n if self._coord.should_stop():\n print('Coordinator stopped')\n sys.stdout.flush()\n self.stop_queues()\n break\n if len(feed_vars) != len(data):\n raise ValueError('Feed vars must be the same length as data.')\n\n if log_this_time and self._summary_writer:\n results = sess.run(ops + [self._summaries],\n dict(zip(feed_vars, data)))\n self._summary_writer.add_summary(results[-1], results[0])\n results = results[:-1]\n else:\n results = sess.run(ops, dict(zip(feed_vars, data)))\n if log_this_time:\n self._log_and_save(sess, results)\n\n # Print the last line if it wasn't just printed\n if print_every and not log_this_time:\n self._log_and_save(sess, results)\n except tf.errors.OutOfRangeError as ex:\n print('Done training -- epoch limit reached %s' % ex.message)\n sys.stdout.flush()\n self.stop_queues()\n except BaseException as ex:\n print('Exception -- stopping threads: %s' % ex, file=sys.stderr)\n sys.stdout.flush()\n self.stop_queues()\n raise\n return results", "def __multiscale_gc_hi2lo_run(self): # , pyed):\n \"\"\"\n Run Graph-Cut segmentation with simplifiyng of high resolution multiscale graph.\n In first step is performed normal GC on low resolution data\n Second step construct finer grid on edges of segmentation from first\n step.\n There is no option for use without `use_boundary_penalties`\n \"\"\"\n # from PyQt4.QtCore import pyqtRemoveInputHook\n # pyqtRemoveInputHook()\n\n self.__msgc_step0_init()\n hard_constraints = self.__msgc_step12_low_resolution_segmentation()\n # ===== high resolution data processing\n seg = self.__msgc_step3_discontinuity_localization()\n nlinks, unariesalt2, msinds = self.__msgc_step45678_hi2lo_construct_graph(\n hard_constraints, seg\n )\n self.__msgc_step9_finish_perform_gc_and_reshape(nlinks, unariesalt2, msinds)", "def preprocess_D_segs(self, generative_model, genomic_data):\n \"\"\"Process P(delDl, delDr|D) into Pi arrays.\n \n Sets the attributes PD_nt_pos_vec, PD_2nd_nt_pos_per_aa_vec, \n min_delDl_given_DdelDr, max_delDl_given_DdelDr, and zeroD_given_D.\n \n Parameters\n ----------\n generative_model : GenerativeModelVDJ\n VDJ generative model class containing the model parameters. \n genomic_data : GenomicDataVDJ\n VDJ genomic data class containing the V, D, and J germline \n sequences and info.\n \n \"\"\"\n \n cutD_genomic_CDR3_segs = genomic_data.cutD_genomic_CDR3_segs\n nt2num = {'A': 0, 'C': 1, 'G': 2, 'T': 3}\n num_dell_pos, num_delr_pos, num_D_genes = generative_model.PdelDldelDr_given_D.shape\n \n #These arrays only include the nt identity information, not the PdelDldelDr_given_D info\n PD_nt_pos_vec = [[]]*num_D_genes\n PD_2nd_nt_pos_per_aa_vec = [[]]*num_D_genes\n for D_in in range(num_D_genes):\n \n current_PD_nt_pos_vec = np.zeros((4, len(cutD_genomic_CDR3_segs[D_in])))\n current_PD_2nd_nt_pos_per_aa_vec = {}\n for aa in self.codons_dict.keys():\n current_PD_2nd_nt_pos_per_aa_vec[aa] = np.zeros((4, len(cutD_genomic_CDR3_segs[D_in])))\n \n for pos, nt in enumerate(cutD_genomic_CDR3_segs[D_in]):\n current_PD_nt_pos_vec[nt2num[nt], pos] = 1\n for ins_nt in 'ACGT':\n for aa in self.codons_dict.keys():\n if ins_nt + cutD_genomic_CDR3_segs[D_in][pos:pos+2] in self.codons_dict[aa]:\n current_PD_2nd_nt_pos_per_aa_vec[aa][nt2num[ins_nt], pos] = 1\n \n PD_nt_pos_vec[D_in] = current_PD_nt_pos_vec\n PD_2nd_nt_pos_per_aa_vec[D_in] = current_PD_2nd_nt_pos_per_aa_vec\n \n min_delDl_given_DdelDr = [[]]*num_D_genes\n max_delDl_given_DdelDr = [[]]*num_D_genes\n zeroD_given_D = [[]]*num_D_genes\n for D_in in range(num_D_genes):\n current_min_delDl_given_delDr = [0]*num_delr_pos\n current_max_delDl_given_delDr = [0]*num_delr_pos\n current_zeroD = 0\n for delr in range(num_delr_pos):\n \n if num_dell_pos > len(cutD_genomic_CDR3_segs[D_in])-delr:\n current_zeroD += generative_model.PdelDldelDr_given_D[len(cutD_genomic_CDR3_segs[D_in])-delr, delr, D_in]\n \n dell = 0\n while generative_model.PdelDldelDr_given_D[dell, delr, D_in]==0 and dell<num_dell_pos-1:\n dell+=1\n if generative_model.PdelDldelDr_given_D[dell, delr, D_in] == 0:\n current_min_delDl_given_delDr[delr] = -1\n else:\n current_min_delDl_given_delDr[delr] = dell\n if current_min_delDl_given_delDr[delr] == -1:\n current_max_delDl_given_delDr[delr] = -1\n else:\n dell = num_dell_pos-1\n while generative_model.PdelDldelDr_given_D[dell, delr, D_in]==0 and dell>=0:\n dell -= 1\n if generative_model.PdelDldelDr_given_D[dell, delr, D_in] == 0:\n current_max_delDl_given_delDr[delr] = -1\n else:\n current_max_delDl_given_delDr[delr] = dell\n \n min_delDl_given_DdelDr[D_in] = current_min_delDl_given_delDr\n max_delDl_given_DdelDr[D_in] = current_max_delDl_given_delDr\n zeroD_given_D[D_in] = current_zeroD\n \n self.PD_nt_pos_vec = PD_nt_pos_vec\n self.PD_2nd_nt_pos_per_aa_vec = PD_2nd_nt_pos_per_aa_vec\n self.min_delDl_given_DdelDr = min_delDl_given_DdelDr \n self.max_delDl_given_DdelDr = max_delDl_given_DdelDr\n self.zeroD_given_D = zeroD_given_D", "def __multiscale_gc_lo2hi_run(self): # , pyed):\n \"\"\"\n Run Graph-Cut segmentation with refinement of low resolution multiscale graph.\n In first step is performed normal GC on low resolution data\n Second step construct finer grid on edges of segmentation from first\n step.\n There is no option for use without `use_boundary_penalties`\n \"\"\"\n # from PyQt4.QtCore import pyqtRemoveInputHook\n # pyqtRemoveInputHook()\n self._msgc_lo2hi_resize_init()\n self.__msgc_step0_init()\n\n hard_constraints = self.__msgc_step12_low_resolution_segmentation()\n # ===== high resolution data processing\n seg = self.__msgc_step3_discontinuity_localization()\n\n self.stats[\"t3.1\"] = (time.time() - self._start_time)\n graph = Graph(\n seg,\n voxelsize=self.voxelsize,\n nsplit=self.segparams[\"block_size\"],\n edge_weight_table=self._msgc_npenalty_table,\n compute_low_nodes_index=True,\n )\n\n # graph.run() = graph.generate_base_grid() + graph.split_voxels()\n # graph.run()\n graph.generate_base_grid()\n self.stats[\"t3.2\"] = (time.time() - self._start_time)\n graph.split_voxels()\n\n self.stats[\"t3.3\"] = (time.time() - self._start_time)\n\n self.stats.update(graph.stats)\n self.stats[\"t4\"] = (time.time() - self._start_time)\n mul_mask, mul_val = self.__msgc_tlinks_area_weight_from_low_segmentation(seg)\n area_weight = 1\n unariesalt = self.__create_tlinks(\n self.img,\n self.voxelsize,\n self.seeds,\n area_weight=area_weight,\n hard_constraints=hard_constraints,\n mul_mask=None,\n mul_val=None,\n )\n # N-links prepared\n self.stats[\"t5\"] = (time.time() - self._start_time)\n un, ind = np.unique(graph.msinds, return_index=True)\n self.stats[\"t6\"] = (time.time() - self._start_time)\n\n self.stats[\"t7\"] = (time.time() - self._start_time)\n unariesalt2_lo2hi = np.hstack(\n [unariesalt[ind, 0, 0].reshape(-1, 1), unariesalt[ind, 0, 1].reshape(-1, 1)]\n )\n nlinks_lo2hi = np.hstack([graph.edges, graph.edges_weights.reshape(-1, 1)])\n if self.debug_images:\n import sed3\n\n ed = sed3.sed3(unariesalt[:, :, 0].reshape(self.img.shape))\n ed.show()\n import sed3\n\n ed = sed3.sed3(unariesalt[:, :, 1].reshape(self.img.shape))\n ed.show()\n # ed = sed3.sed3(seg)\n # ed.show()\n # import sed3\n # ed = sed3.sed3(graph.data)\n # ed.show()\n # import sed3\n # ed = sed3.sed3(graph.msinds)\n # ed.show()\n\n # nlinks, unariesalt2, msinds = self.__msgc_step45678_construct_graph(area_weight, hard_constraints, seg)\n # self.__msgc_step9_finish_perform_gc_and_reshape(nlinks, unariesalt2, msinds)\n self.__msgc_step9_finish_perform_gc_and_reshape(\n nlinks_lo2hi, unariesalt2_lo2hi, graph.msinds\n )\n self._msgc_lo2hi_resize_clean_finish()", "def create_body(arch:Callable, pretrained:bool=True, cut:Optional[Union[int, Callable]]=None):\n \"Cut off the body of a typically pretrained `model` at `cut` (int) or cut the model as specified by `cut(model)` (function).\"\n model = arch(pretrained)\n cut = ifnone(cut, cnn_config(arch)['cut'])\n if cut is None:\n ll = list(enumerate(model.children()))\n cut = next(i for i,o in reversed(ll) if has_pool_type(o))\n if isinstance(cut, int): return nn.Sequential(*list(model.children())[:cut])\n elif isinstance(cut, Callable): return cut(model)\n else: raise NamedError(\"cut must be either integer or a function\")", "def _run_model(iterator, args, tf_args):\n \"\"\"mapPartitions function to run single-node inferencing from a checkpoint/saved_model, using the model's input/output mappings.\n\n Args:\n :iterator: input RDD partition iterator.\n :args: arguments for TFModel, in argparse format\n :tf_args: arguments for TensorFlow inferencing code, in argparse or ARGV format.\n\n Returns:\n An iterator of result data.\n \"\"\"\n single_node_env(tf_args)\n\n logging.info(\"===== input_mapping: {}\".format(args.input_mapping))\n logging.info(\"===== output_mapping: {}\".format(args.output_mapping))\n input_tensor_names = [tensor for col, tensor in sorted(args.input_mapping.items())]\n output_tensor_names = [tensor for tensor, col in sorted(args.output_mapping.items())]\n\n # if using a signature_def_key, get input/output tensor info from the requested signature\n if args.signature_def_key:\n assert args.export_dir, \"Inferencing with signature_def_key requires --export_dir argument\"\n logging.info(\"===== loading meta_graph_def for tag_set ({0}) from saved_model: {1}\".format(args.tag_set, args.export_dir))\n meta_graph_def = get_meta_graph_def(args.export_dir, args.tag_set)\n signature = meta_graph_def.signature_def[args.signature_def_key]\n logging.debug(\"signature: {}\".format(signature))\n inputs_tensor_info = signature.inputs\n logging.debug(\"inputs_tensor_info: {0}\".format(inputs_tensor_info))\n outputs_tensor_info = signature.outputs\n logging.debug(\"outputs_tensor_info: {0}\".format(outputs_tensor_info))\n\n result = []\n\n global global_sess, global_args\n if global_sess and global_args == args:\n # if graph/session already loaded/started (and using same args), just reuse it\n sess = global_sess\n else:\n # otherwise, create new session and load graph from disk\n tf.reset_default_graph()\n sess = tf.Session(graph=tf.get_default_graph())\n if args.export_dir:\n assert args.tag_set, \"Inferencing from a saved_model requires --tag_set\"\n # load graph from a saved_model\n logging.info(\"===== restoring from saved_model: {}\".format(args.export_dir))\n loader.load(sess, args.tag_set.split(','), args.export_dir)\n elif args.model_dir:\n # load graph from a checkpoint\n ckpt = tf.train.latest_checkpoint(args.model_dir)\n assert ckpt, \"Invalid model checkpoint path: {}\".format(args.model_dir)\n logging.info(\"===== restoring from checkpoint: {}\".format(ckpt + \".meta\"))\n saver = tf.train.import_meta_graph(ckpt + \".meta\", clear_devices=True)\n saver.restore(sess, ckpt)\n else:\n raise Exception(\"Inferencing requires either --model_dir or --export_dir argument\")\n global_sess = sess\n global_args = args\n\n # get list of input/output tensors (by name)\n if args.signature_def_key:\n input_tensors = [inputs_tensor_info[t].name for t in input_tensor_names]\n output_tensors = [outputs_tensor_info[output_tensor_names[0]].name]\n else:\n input_tensors = [t + ':0' for t in input_tensor_names]\n output_tensors = [t + ':0' for t in output_tensor_names]\n\n logging.info(\"input_tensors: {0}\".format(input_tensors))\n logging.info(\"output_tensors: {0}\".format(output_tensors))\n\n # feed data in batches and return output tensors\n for tensors in yield_batch(iterator, args.batch_size, len(input_tensor_names)):\n inputs_feed_dict = {}\n for i in range(len(input_tensors)):\n inputs_feed_dict[input_tensors[i]] = tensors[i]\n\n outputs = sess.run(output_tensors, feed_dict=inputs_feed_dict)\n lengths = [len(output) for output in outputs]\n input_size = len(tensors[0])\n assert all([length == input_size for length in lengths]), \"Output array sizes {} must match input size: {}\".format(lengths, input_size)\n python_outputs = [output.tolist() for output in outputs] # convert from numpy to standard python types\n result.extend(zip(*python_outputs)) # convert to an array of tuples of \"output columns\"\n\n return result", "def fit(self, data, debug=False):\n \"\"\"\n Fit each segment. Segments that have not already been explicitly\n added will be automatically added with default model and ytransform.\n\n Parameters\n ----------\n data : pandas.DataFrame\n Must have a column with the same name as `segmentation_col`.\n debug : bool\n If set to true will pass debug to the fit method of each model.\n\n Returns\n -------\n fits : dict of statsmodels.regression.linear_model.OLSResults\n Keys are the segment names.\n\n \"\"\"\n data = util.apply_filter_query(data, self.fit_filters)\n\n unique = data[self.segmentation_col].unique()\n value_counts = data[self.segmentation_col].value_counts()\n\n # Remove any existing segments that may no longer have counterparts\n # in the data. This can happen when loading a saved model and then\n # calling this method with data that no longer has segments that\n # were there the last time this was called.\n gone = set(self._group.models) - set(unique)\n for g in gone:\n del self._group.models[g]\n\n for x in unique:\n if x not in self._group.models and \\\n value_counts[x] > self.min_segment_size:\n self.add_segment(x)\n\n with log_start_finish(\n 'fitting models in segmented model {}'.format(self.name),\n logger):\n return self._group.fit(data, debug=debug)", "def addCuts(self, checkonly):\n \"\"\"add cuts if necessary and return whether model is feasible\"\"\"\n cutsadded = False\n edges = []\n x = self.model.data\n for (i, j) in x:\n if self.model.getVal(x[i, j]) > .5:\n if i != V[0] and j != V[0]:\n edges.append((i, j))\n G = networkx.Graph()\n G.add_edges_from(edges)\n Components = list(networkx.connected_components(G))\n for S in Components:\n S_card = len(S)\n q_sum = sum(q[i] for i in S)\n NS = int(math.ceil(float(q_sum) / Q))\n S_edges = [(i, j) for i in S for j in S if i < j and (i, j) in edges]\n if S_card >= 3 and (len(S_edges) >= S_card or NS > 1):\n cutsadded = True\n if checkonly:\n break\n else:\n self.model.addCons(quicksum(x[i, j] for i in S for j in S if j > i) <= S_card - NS)\n print(\"adding cut for\", S_edges)\n\n return cutsadded", "def graphcut_subprocesses(graphcut_function, graphcut_arguments, processes = None):\n \"\"\"\n Executes multiple graph cuts in parallel.\n This can result in a significant speed-up.\n \n Parameters\n ----------\n graphcut_function : function\n The graph cut to use (e.g. `graphcut_stawiaski`).\n graphcut_arguments : tuple\n List of arguments to pass to the respective subprocesses resp. the ``graphcut_function``.\n processes : integer or None\n The number of processes to run simultaneously, if not supplied, will be the same\n as the number of processors.\n \n Returns\n -------\n segmentations : tuple of ndarray\n The graph-cut segmentation results as list of boolean arraya.\n \"\"\"\n # initialize logger\n logger = Logger.getInstance()\n \n # check and eventually enhance input parameters\n if not processes: processes = multiprocessing.cpu_count()\n if not int == type(processes) or processes <= 0: raise ArgumentError('The number processes can not be zero or negative.')\n \n logger.debug('Executing graph cuts in {} subprocesses.'.format(multiprocessing.cpu_count()))\n \n # creates subprocess pool and execute\n pool = multiprocessing.Pool(processes)\n results = pool.map(graphcut_function, graphcut_arguments)\n \n return results", "def _pare_down_model(self, strain_gempro, genes_to_remove):\n \"\"\"Mark genes as non-functional in a GEM-PRO. If there is a COBRApy model associated with it, the\n COBRApy method delete_model_genes is utilized to delete genes.\n\n Args:\n strain_gempro (GEMPRO): GEMPRO object\n genes_to_remove (list): List of gene IDs to remove from the model\n\n \"\"\"\n # Filter out genes in genes_to_remove which do not show up in the model\n strain_genes = [x.id for x in strain_gempro.genes]\n genes_to_remove.extend(self.missing_in_orthology_matrix)\n genes_to_remove = list(set(genes_to_remove).intersection(set(strain_genes)))\n\n if len(genes_to_remove) == 0:\n log.info('{}: no genes marked non-functional'.format(strain_gempro.id))\n return\n else:\n log.debug('{}: {} genes to be marked non-functional'.format(strain_gempro.id, len(genes_to_remove)))\n\n # If a COBRApy model exists, utilize the delete_model_genes method\n if strain_gempro.model:\n strain_gempro.model._trimmed = False\n strain_gempro.model._trimmed_genes = []\n strain_gempro.model._trimmed_reactions = {}\n\n # Delete genes!\n cobra.manipulation.delete_model_genes(strain_gempro.model, genes_to_remove)\n\n if strain_gempro.model._trimmed:\n log.info('{}: marked {} genes as non-functional, '\n 'deactivating {} reactions'.format(strain_gempro.id, len(strain_gempro.model._trimmed_genes),\n len(strain_gempro.model._trimmed_reactions)))\n # Otherwise, just mark the genes as non-functional\n else:\n for g in genes_to_remove:\n strain_gempro.genes.get_by_id(g).functional = False\n log.info('{}: marked {} genes as non-functional'.format(strain_gempro.id, len(genes_to_remove)))", "def _post_run_hook(self, runtime):\n ''' generates a report showing nine slices, three per axis, of an\n arbitrary volume of `in_files`, with the resulting segmentation\n overlaid '''\n self._anat_file = self.inputs.in_files[0]\n outputs = self.aggregate_outputs(runtime=runtime)\n self._mask_file = outputs.tissue_class_map\n # We are skipping the CSF class because with combination with others\n # it only shows the skullstriping mask\n self._seg_files = outputs.tissue_class_files[1:]\n self._masked = False\n\n NIWORKFLOWS_LOG.info('Generating report for FAST (in_files %s, '\n 'segmentation %s, individual tissue classes %s).',\n self.inputs.in_files,\n outputs.tissue_class_map,\n outputs.tissue_class_files)\n\n return super(FASTRPT, self)._post_run_hook(runtime)" ]
[ 0.6835083961486816, 0.6589675545692444, 0.6549115777015686, 0.6541705131530762, 0.6504920125007629, 0.6443780660629272, 0.6398264765739441, 0.6389582753181458, 0.6380501985549927, 0.6336901187896729, 0.6321241855621338, 0.6307634711265564 ]
it works with seed labels: 0: nothing 1: object 1 - full seeds 2: object 2 - full seeds 3: object 1 - not a training seeds 4: object 2 - not a training seeds
def __set_hard_hard_constraints(self, tdata1, tdata2, seeds): """ it works with seed labels: 0: nothing 1: object 1 - full seeds 2: object 2 - full seeds 3: object 1 - not a training seeds 4: object 2 - not a training seeds """ seeds_mask = (seeds == 1) | (seeds == 3) tdata2[seeds_mask] = np.max(tdata2) + 1 tdata1[seeds_mask] = 0 seeds_mask = (seeds == 2) | (seeds == 4) tdata1[seeds_mask] = np.max(tdata1) + 1 tdata2[seeds_mask] = 0 return tdata1, tdata2
[ "def get_seed_sub(self, label):\r\n \"\"\" Return list of all seeds with specific label\r\n \"\"\"\r\n sx, sy, sz = np.nonzero(self.seeds == label)\r\n\r\n return sx, sy, sz", "def identify(label, column_type = :integer)\n if column_type == :uuid\n NamedSeeds.uuid_v5(label)\n else\n Zlib.crc32(label.to_s) % MAX_ID\n end\n end", "function to_sects(o){\n return order.map(function(label){\n return o[label] ? sect(label, o[label]) : null ;\n }).filter(function(a){ return !!a; });\n}", "def text2labels(text, sents):\n '''\n Marks all characters in given `text`, that doesn't exists within any\n element of `sents` with `1` character, other characters (within sentences)\n will be marked with `0`\n Used in training process\n >>> text = 'привет. меня зовут аня.'\n >>> sents = ['привет.', 'меня зовут аня.']\n >>> labels = text2labels(text, sents)\n >>> ' '.join(text)\n >>> 'п р и в е т . м е н я з о в у т а н я .'\n >>> ' '.join(labels)\n >>> '0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0'\n '''\n labels = [c for c in text]\n for sent in sents:\n start = text.index(sent)\n finish = start + len(sent)\n labels[start:finish] = '0' * len(sent)\n for i, c in enumerate(labels):\n if c != '0':\n labels[i] = '1'\n return labels", "def seed_zoom(seeds, zoom):\n \"\"\"\n Smart zoom for sparse matrix. If there is resize to bigger resolution\n thin line of label could be lost. This function prefers labels larger\n then zero. If there is only one small voxel in larger volume with zeros\n it is selected.\n \"\"\"\n # import scipy\n # loseeds=seeds\n labels = np.unique(seeds)\n # remove first label - 0\n labels = np.delete(labels, 0)\n # @TODO smart interpolation for seeds in one block\n # loseeds = scipy.ndimage.interpolation.zoom(\n # seeds, zoom, order=0)\n loshape = np.ceil(np.array(seeds.shape) * 1.0 / zoom).astype(np.int)\n loseeds = np.zeros(loshape, dtype=np.int8)\n loseeds = loseeds.astype(np.int8)\n for label in labels:\n a, b, c = np.where(seeds == label)\n loa = np.round(a // zoom)\n lob = np.round(b // zoom)\n loc = np.round(c // zoom)\n # loseeds = np.zeros(loshape)\n\n loseeds[loa, lob, loc] += label\n # this is to detect conflict seeds\n loseeds[loseeds > label] = 100\n\n # remove conflict seeds\n loseeds[loseeds > 99] = 0\n\n # import py3DSeedEditor\n # ped = py3DSeedEditor.py3DSeedEditor(loseeds)\n # ped.show()\n\n return loseeds", "def _fix_labels(self):\n \"\"\"For each system, make sure tag _0 is the brightest, and make sure\n system 0 contains the brightest star in the highest-resolution image\n \"\"\"\n for s in self.systems:\n mag0 = np.inf\n n0 = None\n for n in self.get_system(s):\n if isinstance(n.parent, DummyObsNode):\n continue\n mag, _ = n.parent.value\n if mag < mag0:\n mag0 = mag\n n0 = n\n\n # If brightest is not tag _0, then switch them.\n if n0 is not None and n0.tag != 0:\n n_other = self.get_leaf('{}_{}'.format(s,0))\n n_other.tag = n0.tag\n n0.tag = 0", "function(data, options) {\n if (typeof data.length !== 'undefined') {\n if (typeof data[0].length !== 'undefined') {\n this.grouped = true;\n\n // TODO: Find longest?\n this.group_size = data[0].length;\n var o = {}, k, i = 0;\n for (k in options.labels) {\n k = options.labels[k];\n o[k] = data[i];\n i++;\n }\n return o;\n } else {\n return { 'one': data };\n }\n } else {\n return data;\n }\n }", "def _replace_labels(doc):\n \"\"\"Really hacky find-and-replace method that modifies one of the sklearn\n docstrings to change the semantics of labels_ for the subclasses\"\"\"\n lines = doc.splitlines()\n labelstart, labelend = None, None\n foundattributes = False\n for i, line in enumerate(lines):\n stripped = line.strip()\n if stripped == 'Attributes':\n foundattributes = True\n if foundattributes and not labelstart and stripped.startswith('labels_'):\n labelstart = len('\\n'.join(lines[:i])) + 1\n if labelstart and not labelend and stripped == '':\n labelend = len('\\n'.join(lines[:i + 1]))\n\n if labelstart is None or labelend is None:\n return doc\n\n replace = '\\n'.join([\n ' labels_ : list of arrays, each of shape [sequence_length, ]',\n ' The label of each point is an integer in [0, n_clusters).',\n '',\n ])\n return doc[:labelstart] + replace + doc[labelend:]", "def guess_labels(self, doc):\n \"\"\"\n return a prediction of label names\n \"\"\"\n doc = doc.clone() # make sure it can be serialized safely\n return self.index.guess_labels(doc)", "def _load_image_labels(self):\n \"\"\"\n preprocess all ground-truths\n\n Returns:\n ----------\n labels packed in [num_images x max_num_objects x 5] tensor\n \"\"\"\n temp = []\n\n # load ground-truths\n for idx in self.image_set_index:\n label_file = self._label_path_from_index(idx)\n with open(label_file, 'r') as f:\n label = []\n for line in f.readlines():\n temp_label = line.strip().split()\n assert len(temp_label) == 5, \"Invalid label file\" + label_file\n cls_id = int(temp_label[0])\n x = float(temp_label[1])\n y = float(temp_label[2])\n half_width = float(temp_label[3]) / 2\n half_height = float(temp_label[4]) / 2\n xmin = x - half_width\n ymin = y - half_height\n xmax = x + half_width\n ymax = y + half_height\n label.append([cls_id, xmin, ymin, xmax, ymax])\n temp.append(np.array(label))\n return temp", "public static void step(long seed, Neurons[] neurons, DeepLearningModel.DeepLearningModelInfo minfo, boolean training, double[] responses) {\n try {\n for (int i=1; i<neurons.length-1; ++i) {\n neurons[i].fprop(seed, training);\n }\n if (minfo.get_params().autoencoder) {\n neurons[neurons.length - 1].fprop(seed, training);\n if (training) {\n for (int i=neurons.length-1; i>0; --i) {\n neurons[i].bprop();\n }\n }\n } else {\n if (minfo.get_params().classification) {\n ((Neurons.Softmax) neurons[neurons.length - 1]).fprop();\n if (training) {\n for (int i = 1; i < neurons.length - 1; i++)\n Arrays.fill(neurons[i]._e.raw(), 0);\n int target_label;\n if (Double.isNaN(responses[0])) { //missing response\n target_label = Neurons.missing_int_value;\n } else {\n assert ((double) (int) responses[0] == responses[0]); //classification -> integer labels expected\n target_label = (int) responses[0];\n }\n ((Neurons.Softmax) neurons[neurons.length - 1]).bprop(target_label);\n }\n } else {\n ((Neurons.Linear) neurons[neurons.length - 1]).fprop();\n if (training) {\n for (int i = 1; i < neurons.length - 1; i++)\n Arrays.fill(neurons[i]._e.raw(), 0);\n float target_value;\n if (Double.isNaN(responses[0])) { //missing response\n target_value = Neurons.missing_real_value;\n } else {\n target_value = (float) responses[0];\n }\n ((Neurons.Linear) neurons[neurons.length - 1]).bprop(target_value);\n }\n }\n if (training) {\n for (int i=neurons.length-2; i>0; --i)\n neurons[i].bprop();\n }\n }\n }\n catch(RuntimeException ex) {\n Log.warn(ex.getMessage());\n minfo.set_unstable();\n throw new Job.JobCancelledException(\"Canceling job due to numerical instability.\");\n }\n }", "def _load_image_labels(self):\n \"\"\"\n preprocess all ground-truths\n\n Returns:\n ----------\n labels packed in [num_images x max_num_objects x 5] tensor\n \"\"\"\n temp = []\n\n # load ground-truth from xml annotations\n for idx in self.image_set_index:\n label_file = self._label_path_from_index(idx)\n tree = ET.parse(label_file)\n root = tree.getroot()\n size = root.find('size')\n width = float(size.find('width').text)\n height = float(size.find('height').text)\n label = []\n\n for obj in root.iter('object'):\n difficult = int(obj.find('difficult').text)\n # if not self.config['use_difficult'] and difficult == 1:\n # continue\n cls_name = obj.find('name').text\n if cls_name not in self.classes:\n continue\n cls_id = self.classes.index(cls_name)\n xml_box = obj.find('bndbox')\n xmin = float(xml_box.find('xmin').text) / width\n ymin = float(xml_box.find('ymin').text) / height\n xmax = float(xml_box.find('xmax').text) / width\n ymax = float(xml_box.find('ymax').text) / height\n label.append([cls_id, xmin, ymin, xmax, ymax, difficult])\n temp.append(np.array(label))\n return temp" ]
[ 0.7497216463088989, 0.70253586769104, 0.6890901327133179, 0.6859575510025024, 0.6842992901802063, 0.6806407570838928, 0.6781275868415833, 0.6768274307250977, 0.674925684928894, 0.6744183897972107, 0.6728851795196533, 0.6726276278495789 ]
Compute edge values for graph cut tlinks based on image intensity and texture.
def __similarity_for_tlinks_obj_bgr( self, data, voxelsize, # voxels1, voxels2, # seeds, otherfeatures=None ): """ Compute edge values for graph cut tlinks based on image intensity and texture. """ # self.fit_model(data, voxelsize, seeds) # There is a need to have small vaues for good fit # R(obj) = -ln( Pr (Ip | O) ) # R(bck) = -ln( Pr (Ip | B) ) # Boykov2001b # ln is computed in likelihood tdata1 = (-(self.mdl.likelihood_from_image(data, voxelsize, 1))) * 10 tdata2 = (-(self.mdl.likelihood_from_image(data, voxelsize, 2))) * 10 # to spare some memory dtype = np.int16 if np.any(tdata1 > 32760): dtype = np.float32 if np.any(tdata2 > 32760): dtype = np.float32 if self.segparams["use_apriori_if_available"] and self.apriori is not None: logger.debug("using apriori information") gamma = self.segparams["apriori_gamma"] a1 = (-np.log(self.apriori * 0.998 + 0.001)) * 10 a2 = (-np.log(0.999 - (self.apriori * 0.998))) * 10 # logger.debug('max ' + str(np.max(tdata1)) + ' min ' + str(np.min(tdata1))) # logger.debug('max ' + str(np.max(tdata2)) + ' min ' + str(np.min(tdata2))) # logger.debug('max ' + str(np.max(a1)) + ' min ' + str(np.min(a1))) # logger.debug('max ' + str(np.max(a2)) + ' min ' + str(np.min(a2))) tdata1u = (((1 - gamma) * tdata1) + (gamma * a1)).astype(dtype) tdata2u = (((1 - gamma) * tdata2) + (gamma * a2)).astype(dtype) tdata1 = tdata1u tdata2 = tdata2u # logger.debug(' max ' + str(np.max(tdata1)) + ' min ' + str(np.min(tdata1))) # logger.debug(' max ' + str(np.max(tdata2)) + ' min ' + str(np.min(tdata2))) # logger.debug('gamma ' + str(gamma)) # import sed3 # ed = sed3.show_slices(tdata1) # ed = sed3.show_slices(tdata2) del tdata1u del tdata2u del a1 del a2 # if np.any(tdata1 < 0) or np.any(tdata2 <0): # logger.error("Problem with tlinks. Likelihood is < 0") # if self.debug_images: # self.__show_debug_tdata_images(tdata1, tdata2, suptitle="likelihood") return tdata1, tdata2
[ "def __ordered_values_by_indexes(self, data, inds):\n \"\"\"\n Return values (intensities) by indexes.\n\n Used for multiscale graph cut.\n data = [[0 1 1],\n [0 2 2],\n [0 2 2]]\n\n inds = [[0 1 2],\n [3 4 4],\n [5 4 4]]\n\n return: [0, 1, 1, 0, 2, 0]\n\n If the data are not consistent, it will take the maximal value\n\n \"\"\"\n # get unique labels and their first indexes\n # lab, linds = np.unique(inds, return_index=True)\n # compute values by indexes\n # values = data.reshape(-1)[linds]\n\n # alternative slow implementation\n # if there are different data on same index, it will take\n # maximal value\n # lab = np.unique(inds)\n # values = [0]*len(lab)\n # for label in lab:\n # values[label] = np.max(data[inds == label])\n #\n # values = np.asarray(values)\n\n # yet another implementation\n values = [None] * (np.max(inds) + 1)\n\n linear_inds = inds.ravel()\n linear_data = data.ravel()\n for i in range(0, len(linear_inds)):\n # going over all data pixels\n\n if values[linear_inds[i]] is None:\n # this index is found for first\n values[linear_inds[i]] = linear_data[i]\n elif values[linear_inds[i]] < linear_data[i]:\n # here can be changed maximal or minimal value\n values[linear_inds[i]] = linear_data[i]\n\n values = np.asarray(values)\n\n return values", "public void process( T image , GrayF32 intensity ) {\n\t\tint maxFeatures = (int)(maxFeaturesFraction*image.width*image.height);\n\t\tcandidatesLow.reset();\n\t\tcandidatesHigh.reset();\n\t\tthis.image = image;\n\n\t\tif( stride != image.stride ) {\n\t\t\tstride = image.stride;\n\t\t\toffsets = DiscretizedCircle.imageOffsets(radius, image.stride);\n\t\t}\n\t\thelper.setImage(image,offsets);\n\n\t\tfor (int y = radius; y < image.height-radius; y++) {\n\t\t\tint indexIntensity = intensity.startIndex + y*intensity.stride + radius;\n\t\t\tint index = image.startIndex + y*image.stride + radius;\n\t\t\tfor (int x = radius; x < image.width-radius; x++, index++,indexIntensity++) {\n\n\t\t\t\tint result = helper.checkPixel(index);\n\n\t\t\t\tif( result < 0 ) {\n\t\t\t\t\tintensity.data[indexIntensity] = helper.scoreLower(index);\n\t\t\t\t\tcandidatesLow.add(x,y);\n\t\t\t\t} else if( result > 0) {\n\t\t\t\t\tintensity.data[indexIntensity] = helper.scoreUpper(index);\n\t\t\t\t\tcandidatesHigh.add(x,y);\n\t\t\t\t} else {\n\t\t\t\t\tintensity.data[indexIntensity] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// check on a per row basis to reduce impact on performance\n\t\t\tif( candidatesLow.size + candidatesHigh.size >= maxFeatures )\n\t\t\t\tbreak;\n\t\t}\n\t}", "def _compute_fluxes(self):\n \"\"\"\n Compute integrated flux inside ellipse, as well as inside a\n circle defined with the same semimajor axis.\n\n Pixels in a square section enclosing circle are scanned; the\n distance of each pixel to the isophote center is compared both\n with the semimajor axis length and with the length of the\n ellipse radius vector, and integrals are updated if the pixel\n distance is smaller.\n \"\"\"\n\n # Compute limits of square array that encloses circle.\n sma = self.sample.geometry.sma\n x0 = self.sample.geometry.x0\n y0 = self.sample.geometry.y0\n xsize = self.sample.image.shape[1]\n ysize = self.sample.image.shape[0]\n\n imin = max(0, int(x0 - sma - 0.5) - 1)\n jmin = max(0, int(y0 - sma - 0.5) - 1)\n imax = min(xsize, int(x0 + sma + 0.5) + 1)\n jmax = min(ysize, int(y0 + sma + 0.5) + 1)\n\n # Integrate\n if (jmax-jmin > 1) and (imax-imin) > 1:\n y, x = np.mgrid[jmin:jmax, imin:imax]\n radius, angle = self.sample.geometry.to_polar(x, y)\n radius_e = self.sample.geometry.radius(angle)\n\n midx = (radius <= sma)\n values = self.sample.image[y[midx], x[midx]]\n tflux_c = np.ma.sum(values)\n npix_c = np.ma.count(values)\n\n midx2 = (radius <= radius_e)\n values = self.sample.image[y[midx2], x[midx2]]\n tflux_e = np.ma.sum(values)\n npix_e = np.ma.count(values)\n else:\n tflux_e = 0.\n tflux_c = 0.\n npix_e = 0\n npix_c = 0\n\n return tflux_e, tflux_c, npix_e, npix_c", "public void process(GrayF32 intensity ) {\n\n\t\toriginalMin.reset();\n\t\toriginalMax.reset();\n\t\tnonmax.process(intensity,null,null,originalMin,originalMax);\n\n\t\tlocalExtreme.reset();\n\t\tfor (int i = 0; i < originalMin.size; i++) {\n\t\t\tPoint2D_I16 p = originalMin.get(i);\n\t\t\tfloat val = intensity.unsafe_get(p.x,p.y);\n\t\t\tlocalExtreme.grow().set(-val,false,p);\n\t\t}\n\t\tfor (int i = 0; i < originalMax.size; i++) {\n\t\t\tPoint2D_I16 p = originalMax.get(i);\n\t\t\tfloat val = intensity.unsafe_get(p.x, p.y);\n\t\t\tlocalExtreme.grow().set(val,true,p);\n\t\t}\n\n\t\tif( localExtreme.size > maxTotalFeatures ) {\n\t\t\tQuickSelect.select(localExtreme.data, maxTotalFeatures, localExtreme.size);\n\t\t\tlocalExtreme.size = maxTotalFeatures;\n\t\t}\n\t}", "private void calc() {\n int hMin = (int) ((this.cImage.getHeight()) / 4.0);\n int hMax = (int) ((this.cImage.getHeight()) * 3.0 / 4.0);\n init();\n\n for (int y = hMin; y < hMax; y++) {\n for (int x = 1; x < (this.cImage.getWidth() - 2); x++) {\n // only lower edges are considered\n if (ImageUtil.isBlack(this.cImage, x, y)) {\n if (!ImageUtil.isBlack(this.cImage, x, y + 1)) {\n calc(x, y);\n }\n }\n }\n }\n\n }", "def _calc_texture_gradient(img):\n \"\"\"\n calculate texture gradient for entire image\n\n The original SelectiveSearch algorithm proposed Gaussian derivative\n for 8 orientations, but we use LBP instead.\n\n output will be [height(*)][width(*)]\n \"\"\"\n ret = numpy.zeros((img.shape[0], img.shape[1], img.shape[2]))\n\n for colour_channel in (0, 1, 2):\n ret[:, :, colour_channel] = skimage.feature.local_binary_pattern(\n img[:, :, colour_channel], 8, 1.0)\n\n return ret", "def _calc_grad_tiled(self, img, t_grad, tile_size=512):\n '''Compute the value of tensor t_grad over the image in a tiled way.\n Random shifts are applied to the image to blur tile boundaries over \n multiple iterations.'''\n sz = tile_size\n h, w = img.shape[:2]\n sx, sy = np.random.randint(sz, size=2)\n img_shift = np.roll(np.roll(img, sx, 1), sy, 0)\n grad = np.zeros_like(img)\n for y in range(0, max(h-sz//2, sz),sz):\n for x in range(0, max(w-sz//2, sz),sz):\n sub = img_shift[y:y+sz,x:x+sz]\n g = self._session.run(t_grad, {self._t_input:sub})\n grad[y:y+sz,x:x+sz] = g\n return np.roll(np.roll(grad, -sx, 1), -sy, 0)", "function calcCutValue(t, g, child) {\n var childLab = t.node(child);\n var parent = childLab.parent;\n // True if the child is on the tail end of the edge in the directed graph\n var childIsTail = true;\n // The graph's view of the tree edge we're inspecting\n var graphEdge = g.edge(child, parent);\n // The accumulated cut value for the edge between this node and its parent\n var cutValue = 0;\n\n if (!graphEdge) {\n childIsTail = false;\n graphEdge = g.edge(parent, child);\n }\n\n cutValue = graphEdge.weight;\n\n _.forEach(g.nodeEdges(child), function(e) {\n var isOutEdge = e.v === child,\n other = isOutEdge ? e.w : e.v;\n\n if (other !== parent) {\n var pointsToHead = isOutEdge === childIsTail,\n otherWeight = g.edge(e).weight;\n\n cutValue += pointsToHead ? otherWeight : -otherWeight;\n if (isTreeEdge(t, child, other)) {\n var otherCutValue = t.edge(child, other).cutvalue;\n cutValue += pointsToHead ? -otherCutValue : otherCutValue;\n }\n }\n });\n\n return cutValue;\n}", "def _calc_texture_hist(img):\n \"\"\"\n calculate texture histogram for each region\n\n calculate the histogram of gradient for each colours\n the size of output histogram will be\n BINS * ORIENTATIONS * COLOUR_CHANNELS(3)\n \"\"\"\n BINS = 10\n\n hist = numpy.array([])\n\n for colour_channel in (0, 1, 2):\n\n # mask by the colour channel\n fd = img[:, colour_channel]\n\n # calculate histogram for each orientation and concatenate them all\n # and join to the result\n hist = numpy.concatenate(\n [hist] + [numpy.histogram(fd, BINS, (0.0, 1.0))[0]])\n\n # L1 Normalize\n hist = hist / len(img)\n\n return hist", "def compute_edge_colors(self):\n \"\"\"Compute the edge colors.\"\"\"\n data = [self.graph.edges[n][self.edge_color] for n in self.edges]\n data_reduced = sorted(list(set(data)))\n\n dtype = infer_data_type(data)\n n_grps = num_discrete_groups(data)\n if dtype == \"categorical\" or dtype == \"ordinal\":\n if n_grps <= 8:\n cmap = get_cmap(\n cmaps[\"Accent_{0}\".format(n_grps)].mpl_colormap\n )\n else:\n cmap = n_group_colorpallet(n_grps)\n elif dtype == \"continuous\" and not is_data_diverging(data):\n cmap = get_cmap(cmaps[\"weights\"])\n\n for d in data:\n idx = data_reduced.index(d) / n_grps\n self.edge_colors.append(cmap(idx))\n # Add colorbar if required.\n logging.debug(\"length of data_reduced: {0}\".format(len(data_reduced)))\n logging.debug(\"dtype: {0}\".format(dtype))\n if len(data_reduced) > 1 and dtype == \"continuous\":\n self.sm = plt.cm.ScalarMappable(\n cmap=cmap,\n norm=plt.Normalize(\n vmin=min(data_reduced),\n vmax=max(data_reduced), # noqa # noqa\n ),\n )\n self.sm._A = []", "def compute_values(edge_compatibility, v):\n \"\"\"Compute values. If edge compatibilities is just adjacency, we get ggnn.\n\n Args:\n edge_compatibility: A tensor of shape [batch, num_transforms, length, depth]\n v: A tensor of shape [batch, num_transforms, length, depth]\n\n Returns:\n output: A [batch, length, depth] tensor\n \"\"\"\n\n # Computes the incoming value vectors for each node by weighting them\n # according to the attention weights. These values are still segregated by\n # edge type.\n # Shape = [B, T, N, V].\n all_edge_values = tf.matmul(tf.to_float(edge_compatibility), v)\n\n # Combines the weighted value vectors together across edge types into a\n # single N x V matrix for each batch.\n output = tf.reduce_sum(all_edge_values, axis=1) # Shape [B, N, V].\n return output", "def __create_nlinks(self, data, inds=None, boundary_penalties_fcn=None):\n \"\"\"\n Compute nlinks grid from data shape information. For boundary penalties\n are data (intensities) values are used.\n\n ins: Default is None. Used for multiscale GC. This are indexes of\n multiscale pixels. Next example shows one superpixel witn index 2.\n inds = [\n [1 2 2],\n [3 2 2],\n [4 5 6]]\n\n boundary_penalties_fcn: is function with one argument - axis. It can\n it can be used for setting penalty weights between neighbooring\n pixels.\n\n \"\"\"\n # use the gerneral graph algorithm\n # first, we construct the grid graph\n start = time.time()\n if inds is None:\n inds = np.arange(data.size).reshape(data.shape)\n # if not self.segparams['use_boundary_penalties'] and \\\n # boundary_penalties_fcn is None :\n if boundary_penalties_fcn is None:\n # This is faster for some specific format\n edgx = np.c_[inds[:, :, :-1].ravel(), inds[:, :, 1:].ravel()]\n edgy = np.c_[inds[:, :-1, :].ravel(), inds[:, 1:, :].ravel()]\n edgz = np.c_[inds[:-1, :, :].ravel(), inds[1:, :, :].ravel()]\n\n else:\n logger.info(\"use_boundary_penalties\")\n\n bpw = self.segparams[\"boundary_penalties_weight\"]\n\n bpa = boundary_penalties_fcn(2)\n # id1=inds[:, :, :-1].ravel()\n edgx = np.c_[\n inds[:, :, :-1].ravel(),\n inds[:, :, 1:].ravel(),\n # cc * np.ones(id1.shape)\n bpw * bpa[:, :, 1:].ravel(),\n ]\n\n bpa = boundary_penalties_fcn(1)\n # id1 =inds[:, 1:, :].ravel()\n edgy = np.c_[\n inds[:, :-1, :].ravel(),\n inds[:, 1:, :].ravel(),\n # cc * np.ones(id1.shape)]\n bpw * bpa[:, 1:, :].ravel(),\n ]\n\n bpa = boundary_penalties_fcn(0)\n # id1 = inds[1:, :, :].ravel()\n edgz = np.c_[\n inds[:-1, :, :].ravel(),\n inds[1:, :, :].ravel(),\n # cc * np.ones(id1.shape)]\n bpw * bpa[1:, :, :].ravel(),\n ]\n\n # import pdb; pdb.set_trace()\n edges = np.vstack([edgx, edgy, edgz]).astype(np.int32)\n # edges - seznam indexu hran, kteres spolu sousedi\\\n elapsed = time.time() - start\n self.stats[\"_create_nlinks time\"] = elapsed\n logger.info(\"__create nlinks time \" + str(elapsed))\n return edges" ]
[ 0.6722548007965088, 0.6709698438644409, 0.6678282618522644, 0.6651525497436523, 0.6602543592453003, 0.6581569910049438, 0.6538912057876587, 0.6536920666694641, 0.6516335606575012, 0.6476464867591858, 0.6469390988349915, 0.6459125280380249 ]
End of preview. Expand in Data Studio

CodeSearchNet Hard Negatives (Filtered) by Lumees AI

Dataset Summary

This dataset is a processed version of the CodeSearchNet dataset, enhanced with Hard Negative Mining to facilitate the training of state-of-the-art code retrieval models.

It was created by Lumees AI to improve the ability of embedding models to distinguish between syntactically similar but functionally different code snippets.

  • Developer: Lumees AI
  • Authors: Hasan Kurşun, Kerem Berkay Yanık
  • Contact: hello@lumees.io
  • Source Data: CodeSearchNet (Train split)
  • Total Samples: ~1.88M triplets/tuples

Dataset Structure

The dataset is provided in .jsonl format. Each line represents a training sample containing a natural language query, the positive ground truth code, and a list of mined hard negatives.

Data Fields

  • query (string): The natural language docstring/description of the function.
  • pos (string): The positive (ground truth) code snippet.
  • neg (list of strings): A list of hard negative code snippets (semantically similar to the query but incorrect).
  • scores (list of floats): The cosine similarity scores of the negative candidates against the query (computed by the mining model).

Example Instance

{
  "query": "CommentsView sub-view (will be used recursively)",
  "pos": "function ThreadBranchView(vm) { ... }",
  "neg": [
    "function CommentReplyView(vm, comment) { ... }",
    "public function viewAction() { ... }"
  ],
  "scores": [0.7502, 0.7481]
}

Methodology & Creation

Source Model

The mining process utilized Alibaba-NLP/gte-multilingual-base, a high-performance embedding model, to generate vector representations for both queries and code.

Mining Process

The dataset was constructed using a dense retrieval approach on the entire CodeSearchNet training corpus across 6 languages (Python, Java, Go, PHP, Ruby, JavaScript).

  1. Embedding: All code snippets in the corpus were encoded into dense vectors.
  2. Retrieval: For every query, we retrieved the top 50 semantic candidates from the corpus using GPU-accelerated Matrix Multiplication.
  3. Filtration:
    • Self-Exclusion: The positive ground truth was removed from results.
    • Duplicate Removal: Exact string duplicates of the positive code were removed.
    • Score Thresholding:
      • Max Similarity (0.95): Candidates with scores above 0.95 were discarded to avoid False Negatives (valid code that is too similar to the ground truth).
      • Min Similarity (0.35): Candidates with scores below 0.35 were discarded to ensure the negatives are "hard" enough to be useful for training (avoiding easy negatives).
  4. Selection: Up to the top 12 valid hard negatives were selected for each query.

Intended Use

This dataset is optimized for:

  • Contrastive Learning: Fine-tuning embedding models using losses like MultipleNegativesRankingLoss or TripletLoss.
  • Code Retrieval: Improving search relevance in IDEs or code search engines.
  • Cross-Lingual Alignment: The dataset includes cross-lingual negatives (e.g., a Python query retrieving similar PHP code), helping models learn language-agnostic semantic features.

Licensing

This dataset adheres to the licensing terms of the original CodeSearchNet dataset (MIT/Permissive). Users should verify specific licensing requirements for individual code snippets if used for commercial code generation.

Citation

If you use this dataset, please cite Lumees AI and the original CodeSearchNet paper:

@misc{lumees2025hardnegatives,
  author = {Hasan KURŞUN, Kerem Berkay YANIK},
  title = {CodeSearchNet Hard Negatives (Filtered)},
  year = {2025},
  publisher = {Lumees AI},
  howpublished = {\url{[https://lumees.io](https://lumees.io)}},
  email = {hello@lumees.io}
}

@article{husain2019codesearchnet,
  title={CodeSearchNet Challenge: Evaluating the State of Semantic Code Search},
  author={Husain, Hamel and Wu, Ho-Hsiang and Gazit, Tiferet and Allamanis, Miltiadis and Brockschmidt, Marc},
  journal={arXiv preprint arXiv:1909.09436},
  year={2019}
}
Downloads last month
63

Collection including lumees/codesearchnet-hard-negatives