def parse(self, request: Metamorphing, settings: dict) -> List[Tuple[models.Model, str]]: self.progress("Building Graph") array: xr.DataArray = request.representation.array raise LarvikError("NOT IMPLEMENTED YET") self.progress(f"Trying to Metamorph Array of Shape {array.shape}") print(array.dtype) if "t" in array.dims: array = array.sel(t=0) if "z" not in array.dims: raise LarvikError("This is not a Z-Stack") self.helpers.addChannel(tosize=3) # Making sure we have enough self.progress(f"Scaling") # Rescaling to classic Array Size array = array * 255 array.astype("uint8") self.progress(f"Swapping Axes") array = array.transpose("x", "y", "z", "channel") array.compute() shape_3d = array.shape[0:3] self.progress(f"New Shape is {shape_3d}") rgb_dtype = np.dtype([('R', 'u1'), ('G', 'u1'), ('B', 'u1')]) array = np.ascontiguousarray(array, dtype='u1') self.progress("Continuing Array") array = array.view(rgb_dtype).reshape(shape_3d) nifti = nib.Nifti1Image(array, np.eye(4)) niftipaths = "sample-{0}_representation-{1}_nodeid-{2}.nii.gz".format( request.sample.id, request.representation.id, request.nodeid) niftipath = os.path.join(NIFTI_ROOT, niftipaths) nib.save(nifti, niftipath) raise NotImplementedError("BROKEN") MEDIA_ROOT = "None" niftiwebpath = os.path.join(os.path.join(MEDIA_ROOT, "/nifti"), niftipaths) name = "Exhibit of" + request.representation.name exhibit = Exhibit.objects.create( representation=request.representation, name=name, creator=request.creator, nodeid=request.nodeid, shape=request.representation.shape, sample=request.sample, experiment=request.representation.experiment, niftipath=niftiwebpath) return [(exhibit, "create")]
async def parse(self, request: Transforming, settings: dict) -> Dict[str, Any]: rep = request.representation roi = request.roi shape = json.loads(rep.shape) z_size = shape[3] vectors = json.loads(roi.vectors) vertices = [[key["x"], key["y"]] for key in vectors] scale = settings.get("scale", 10) # We Have to Slice the Array first in order to make the transformation work lowerBound1: int = settings.get("lower", 0) upperBound1: int = settings.get("upper", z_size - 1) if upperBound1 is None: raise LarvikError("Upper Bound Not correctly set") if lowerBound1 is None: raise LarvikError("Lower Bound Not correctly set") if lowerBound1 > upperBound1: lowerBound = upperBound1 upperBound = lowerBound1 else: lowerBound = lowerBound1 upperBound = upperBound1 await self.progress("Getting array from file system") array = rep.array if "z" in array.dims: array = array.sel(z=slice(lowerBound, upperBound)).max(dim="z") if "t" in array.dims: array = array.sel(t=0) if "c" in array.dims: array = array.sel(c=[0, 1, 2]) # Todo Probably not necessary self.logger.info("Collection Array of Shape {0} ".format(array.shape)) self.logger.info("With Vertices like {0}".format(vertices)) self.logger.info("Scale: {0}".format(scale)) await self.progress("Selecting") self.logger.info("Maxed array of shape {0}".format(array.shape)) array = np.float64(array) await self.progress("Transforming") image, boxwidths, pixelwidths, boxes = translateImageFromLine( array, vertices, int(scale)) array = xr.DataArray(image, dims=["x", "y", "c"]) return {"array": array}
def start(self, request: Importing, settings: dict): creator: User = request.creator locker = request.locker # Media Path of Nginx is solely MEDIA, this one here is /code/media base_dir = os.path.join(FILES_ROOT, creator.username) self.progress(base_dir) self.progress("Starting") self.progress(os.listdir(base_dir)) filelist = [(filename, os.path.join(base_dir, filename)) for filename in os.listdir(base_dir)] if len(filelist) == 0: raise LarvikError("No Files in directory.") self.logger.info("Files To Import {0}".format(filelist)) # %% progress = self.progress updateModel = self.updateModel # %% def moveFileToLocker(path, name): if os.path.exists(path): progress("Moving file " + path) directory = "{0}/{1}/".format(request.creator.id, request.locker.id) raise NotImplementedError("Updated Here") directory = os.path.join("sd", directory) if not os.path.exists(directory): os.makedirs(directory) new_path = os.path.join(directory, os.path.basename(name)) shutil.move(path, new_path) name = name if name else os.path.basename(path) image = BioImage.objects.create(file=new_path, creator=request.creator, locker=request.locker, name=os.path.basename(name), nodeid=request.nodeid) image.save() updateModel(image, "created") return image bioimages = [] for file in filelist: path = file[1] name = file[0] bioimages.append((moveFileToLocker(path, name), "create")) self.progress("Done") return {"BioImage": filelist}
def parse(self, request: Straining, settings: dict) -> Dict[str, Any]: print(str(self.c)) transformation_image = request.transformation.loadArray() height = 0 ndim = 2 if len(transformation_image.shape) > 3 or len( transformation_image.shape) < 2: raise LarvikError( "This is not a valid transformation. Shape exceeds the available dimensions" ) if len(transformation_image.shape) == 3: height, width, channels = transformation_image.shape ndim = 3 if len(transformation_image.shape) == 2: height, width = transformation_image.shape channels = 0 ndim = 2 # this takes the middle part of the picture middleup = int((height / 2) - (height / 4)) middledown = int((height / 2) + (height / 4)) # trimm image according to needs if ndim == 3: trimmedimage = transformation_image[middleup:middledown, :, :] else: trimmedimage = transformation_image[middleup:middledown, :] np.seterr(divide='ignore', invalid='ignore') # error level if a pixelvalue is 0 averages = np.max(trimmedimage, axis=0) intensity = averages / averages.max(axis=0) if "channels" in settings: self.logger.info("Original Intensitycurve had shape of {0}".format( intensity.shape)) selectedchannels = list( map(lambda item: item["value"], settings["channels"])) self.logger.info("Selecting Channels {0}".format(selectedchannels)) intensity = np.take(intensity, selectedchannels, axis=1) self.logger.info("Intensitycurves now has shape of {0}".format( intensity.shape)) return {"array": intensity}
def reflection_update_or_create(image, request: Mutating, settings) -> [(Reflection, str)]: """ Tries to fetch a room for the user, checking permissions along the way. """ reflection: Reflection = Reflection.objects.filter( transformation=request.transformation).filter( nodeid=request.nodeid).first() method = "update" if reflection is None: #TODO make creation of outputvid reflection = Reflection.objects.create( transformation=request.transformation, creator=request.creator, nodeid=request.nodeid, roi=request.transformation.roi, sample=request.sample, shape=request.transformation.shape, experiment=request.transformation.experiment) method = "create" if reflection is not None: #TODO: update array of output path = "sample-{0}_transformation-{1}_node-{2}".format( str(reflection.sample.id), str(reflection.transformation.id), str(request.nodeid)) img_io = io.BytesIO() image.save(img_io, format='jpeg', quality=100) thumb_file = InMemoryUploadedFile(img_io, None, path + ".jpeg", 'image/jpeg', img_io.tell, None) reflection.image = thumb_file reflection.save() print("YES") else: raise LarvikError("FATAL ERROR SOMEWHERE") return [(reflection, method)]
def filter(array: xr.DataArray, settings: dict, manager = LarvikManager()) -> xr.DataArray: if "z" not in array.dims: raise LarvikError("The Data has no Z Dimensions") return array.max(dim="z", keep_attrs=True)