This function will convert siemens 4d series to a nifti
    Some inspiration on which fields can be used was taken from
    http://slicer.org/doc/html/DICOMDiffusionVolumePlugin_8py_source.html
965700
def _classic_4d_to_nifti(grouped_dicoms, output_file):
    
    # Get the sorted mosaics
    all_dicoms = [i for sl in grouped_dicoms for i in sl]  # combine into 1 list for validating
    common.validate_orientation(all_dicoms)

    # Create mosaic block
    logger.info('Creating data block')
    full_block = _classic_get_full_block(grouped_dicoms)

    logger.info('Creating affine')
    # Create the nifti header info
    affine, slice_increment = common.create_affine(grouped_dicoms[0])

    logger.info('Creating nifti')
    # Convert to nifti
    nii_image = nibabel.Nifti1Image(full_block, affine)
    common.set_tr_te(nii_image, float(grouped_dicoms[0][0].RepetitionTime), float(grouped_dicoms[0][0].EchoTime))
    logger.info('Saving nifti to disk')
    # Save to disk
    if output_file is not None:
        nii_image.to_filename(output_file)

    if _is_diffusion_imaging(grouped_dicoms[0][0]):
        logger.info('Creating bval en bvec')
        bval_file = None
        bvec_file = None
        if output_file is not None:
            base_path = os.path.dirname(output_file)
            base_name = os.path.splitext(os.path.splitext(os.path.basename(output_file))[0])[0]
            logger.info('Creating bval en bvec files')
            bval_file = '%s/%s.bval' % (base_path, base_name)
            bvec_file = '%s/%s.bvec' % (base_path, base_name)

        bval = _create_bvals(grouped_dicoms, bval_file)
        bvec = _create_bvecs(grouped_dicoms, bvec_file)

        return {'NII_FILE': output_file,
                'BVAL_FILE': bval_file,
                'BVEC_FILE': bvec_file,
                'NII': nii_image,
                'BVAL': bval,
                'BVEC': bvec,
                'MAX_SLICE_INCREMENT': slice_increment}

    return {'NII_FILE': output_file,
            'NII': nii_image,
            'MAX_SLICE_INCREMENT': slice_increment}
302948
def convert_tscube_old(infile, outfile):
    """"""
    inhdulist = fits.open(infile)

    # If already in the new-style format just write and exit
    if 'DLOGLIKE_SCAN' in inhdulist['SCANDATA'].columns.names:
        if infile != outfile:
            inhdulist.writeto(outfile, clobber=True)
        return

    # Get stuff out of the input file
    nrows = inhdulist['SCANDATA']._nrows
    nebins = inhdulist['EBOUNDS']._nrows
    npts = inhdulist['SCANDATA'].data.field('NORMSCAN').shape[1] / nebins

    emin = inhdulist['EBOUNDS'].data.field('e_min') / 1E3
    emax = inhdulist['EBOUNDS'].data.field('e_max') / 1E3
    eref = np.sqrt(emin * emax)
    dnde_emin = inhdulist['EBOUNDS'].data.field('E_MIN_FL')
    dnde_emax = inhdulist['EBOUNDS'].data.field('E_MAX_FL')
    index = np.log(dnde_emin / dnde_emax) / np.log(emin / emax)

    flux = PowerLaw.eval_flux(emin, emax, [dnde_emin, index], emin)
    eflux = PowerLaw.eval_eflux(emin, emax, [dnde_emin, index], emin)
    dnde = PowerLaw.eval_dnde(np.sqrt(emin * emax), [dnde_emin, index], emin)

    ts_map = inhdulist['PRIMARY'].data.reshape((nrows))
    ok_map = inhdulist['TSMAP_OK'].data.reshape((nrows))
    n_map = inhdulist['N_MAP'].data.reshape((nrows))
    errp_map = inhdulist['ERRP_MAP'].data.reshape((nrows))
    errn_map = inhdulist['ERRN_MAP'].data.reshape((nrows))
    err_map = np.ndarray((nrows))
    m = errn_map > 0
    err_map[m] = 0.5 * (errp_map[m] + errn_map[m])
    err_map[~m] = errp_map[~m]
    ul_map = n_map + 2.0 * errp_map

    ncube = np.rollaxis(inhdulist['N_CUBE'].data,
                        0, 3).reshape((nrows, nebins))
    errpcube = np.rollaxis(
        inhdulist['ERRPCUBE'].data, 0, 3).reshape((nrows, nebins))
    errncube = np.rollaxis(
        inhdulist['ERRNCUBE'].data, 0, 3).reshape((nrows, nebins))
    tscube = np.rollaxis(inhdulist['TSCUBE'].data,
                         0, 3).reshape((nrows, nebins))
    nll_cube = np.rollaxis(
        inhdulist['NLL_CUBE'].data, 0, 3).reshape((nrows, nebins))
    ok_cube = np.rollaxis(
        inhdulist['TSCUBE_OK'].data, 0, 3).reshape((nrows, nebins))

    ul_cube = ncube + 2.0 * errpcube
    m = errncube > 0
    errcube = np.ndarray((nrows, nebins))
    errcube[m] = 0.5 * (errpcube[m] + errncube[m])
    errcube[~m] = errpcube[~m]

    norm_scan = inhdulist['SCANDATA'].data.field(
        'NORMSCAN').reshape((nrows, npts, nebins)).swapaxes(1, 2)
    nll_scan = inhdulist['SCANDATA'].data.field(
        'NLL_SCAN').reshape((nrows, npts, nebins)).swapaxes(1, 2)

    # Adjust the "EBOUNDS" hdu
    columns = inhdulist['EBOUNDS'].columns
    columns.add_col(fits.Column(name=str('e_ref'),
                                format='E', array=eref * 1E3,
                                unit='keV'))
    columns.add_col(fits.Column(name=str('ref_flux'),
                                format='D', array=flux,
                                unit='ph / (cm2 s)'))
    columns.add_col(fits.Column(name=str('ref_eflux'),
                                format='D', array=eflux,
                                unit='MeV / (cm2 s)'))
    columns.add_col(fits.Column(name=str('ref_dnde'),
                                format='D', array=dnde,
                                unit='ph / (MeV cm2 s)'))

    columns.change_name('E_MIN_FL', str('ref_dnde_e_min'))
    columns.change_unit('ref_dnde_e_min', 'ph / (MeV cm2 s)')
    columns.change_name('E_MAX_FL', str('ref_dnde_e_max'))
    columns.change_unit('ref_dnde_e_max', 'ph / (MeV cm2 s)')
    columns.change_name('NPRED', str('ref_npred'))

    hdu_e = fits.BinTableHDU.from_columns(columns, name='EBOUNDS')

    # Make the "FITDATA" hdu
    columns = fits.ColDefs([])

    columns.add_col(fits.Column(
        name=str('fit_ts'), format='E', array=ts_map))
    columns.add_col(fits.Column(
        name=str('fit_status'), format='E', array=ok_map))
    columns.add_col(fits.Column(
        name=str('fit_norm'), format='E', array=n_map))
    columns.add_col(fits.Column(
        name=str('fit_norm_err'), format='E', array=err_map))
    columns.add_col(fits.Column(
        name=str('fit_norm_errp'), format='E', array=errp_map))
    columns.add_col(fits.Column(
        name=str('fit_norm_errn'), format='E', array=errn_map))
    hdu_f = fits.BinTableHDU.from_columns(columns, name='FITDATA')

    # Make the "SCANDATA" hdu
    columns = fits.ColDefs([])

    columns.add_col(fits.Column(name=str('ts'),
                                format='%iE' % nebins, array=tscube,
                                dim=str('(%i)' % nebins)))

    columns.add_col(fits.Column(name=str('bin_status'),
                                format='%iE' % nebins, array=ok_cube,
                                dim=str('(%i)' % nebins)))

    columns.add_col(fits.Column(name=str('norm'),
                                format='%iE' % nebins, array=ncube,
                                dim=str('(%i)' % nebins)))

    columns.add_col(fits.Column(name=str('norm_ul'),
                                format='%iE' % nebins, array=ul_cube,
                                dim=str('(%i)' % nebins)))

    columns.add_col(fits.Column(name=str('norm_err'),
                                format='%iE' % nebins, array=errcube,
                                dim=str('(%i)' % nebins)))

    columns.add_col(fits.Column(name=str('norm_errp'),
                                format='%iE' % nebins, array=errpcube,
                                dim=str('(%i)' % nebins)))

    columns.add_col(fits.Column(name=str('norm_errn'),
                                format='%iE' % nebins, array=errncube,
                                dim=str('(%i)' % nebins)))

    columns.add_col(fits.Column(name=str('loglike'),
                                format='%iE' % nebins, array=nll_cube,
                                dim=str('(%i)' % nebins)))

    columns.add_col(fits.Column(name=str('norm_scan'),
                                format='%iE' % (nebins * npts),
                                array=norm_scan,
                                dim=str('(%i,%i)' % (npts, nebins))))

    columns.add_col(fits.Column(name=str('dloglike_scan'),
                                format='%iE' % (nebins * npts),
                                array=nll_scan,
                                dim=str('(%i,%i)' % (npts, nebins))))

    hdu_s = fits.BinTableHDU.from_columns(columns, name='SCANDATA')

    hdulist = fits.HDUList([inhdulist[0],
                            hdu_s,
                            hdu_f,
                            inhdulist["BASELINE"],
                            hdu_e])

    hdulist['SCANDATA'].header['UL_CONF'] = 0.95

    hdulist.writeto(outfile, clobber=True)

    return hdulist
15564
def _GenNetflowRecordV9(cls, lengths_list):
    
    _fields_desc = []
    for j, k in lengths_list:
        _f_data = NetflowV9TemplateFieldDecoders.get(k, None)
        _f_type, _f_args = (
            _f_data if isinstance(_f_data, tuple) else (_f_data, [])
        )
        _f_kwargs = {}
        if _f_type:
            if issubclass(_f_type, _AdjustableNetflowField):
                _f_kwargs["length"] = j
            _fields_desc.append(
                _f_type(
                    NetflowV910TemplateFieldTypes.get(k, "unknown_data"),
                    0, *_f_args, **_f_kwargs
                )
            )
        else:
            _fields_desc.append(
                _CustomStrFixedLenField(
                    NetflowV910TemplateFieldTypes.get(k, "unknown_data"),
                    b"", length=j
                )
            )

    # This will act exactly like a NetflowRecordV9, but has custom fields
    class NetflowRecordV9I(cls):
        fields_desc = _fields_desc
        match_subclass = True
    NetflowRecordV9I.name = cls.name
    NetflowRecordV9I.__name__ = cls.__name__
    return NetflowRecordV9I
278069
def load_siemens_dicom(filename):
    
    # the .IMA format is a DICOM standard, unfortunately most of the information is contained inside a private and very
    # complicated header with its own data storage format, we have to get that information out along with the data
    # start by reading in the DICOM file completely
    dataset = pydicom.dicomio.read_file(filename)
    # now look through the tags (0029, 00xx) to work out which xx refers to the csa header
    # xx seems to start at 10 for Siemens
    xx = 0x0010
    header_index = 0
    while (0x0029, xx) in dataset:
        if dataset[0x0029, xx].value == "SIEMENS CSA HEADER":
            header_index = xx
        xx += 1
    # check that we have found the header
    if header_index == 0:
        raise KeyError("Could not find header index")
    # now we know which tag contains the CSA image header info: (0029, xx10)
    csa_header_bytes = dataset[0x0029, 0x0100 * header_index + 0x0010].value
    csa_header = read_csa_header(csa_header_bytes)
    #for key, value in csa_header.items():
    #    print("%s : %s" % (str(key), str(value)))
    # we can also get the series header info: (0029, xx20), but this seems to be mostly pretty boring

    # now we can work out the shape of the data (slices, rows, columns, fid_points)
    data_shape = (csa_header["SpectroscopyAcquisitionOut-of-planePhaseSteps"],
                  csa_header["Rows"],
                  csa_header["Columns"],
                  csa_header["DataPointColumns"],
                  )

    # now look through the tags (0029, 00xx) to work out which xx refers to the csa header
    # xx seems to start at 10 for Siemens
    xx = 0x0010
    data_index = 0
    while (0x7fe1, xx) in dataset:
        if dataset[0x7fe1, xx].value == "SIEMENS CSA NON-IMAGE":
            data_index = xx
        xx += 1
    # check that we have found the data
    if data_index == 0:
        raise KeyError("Could not find data index")
    # extract the actual data bytes
    csa_data_bytes = dataset[0x7fe1, 0x0100 * data_index + 0x0010].value
    # the data is stored as a list of 4 byte floats in (real, imaginary) pairs
    data_floats = struct.unpack("<%df" % (len(csa_data_bytes) / 4), csa_data_bytes)
    # form an iterator which will provide the numbers one at a time, then an iterator which calls that iterator twice
    # each cycle to give a complex pair
    data_iter = iter(data_floats)
    complex_iter = (complex(r, i) for r, i in zip(data_iter, data_iter))
    # give this iterator to numpy to build the data array
    complex_data = numpy.fromiter(complex_iter, "complex128", int(len(csa_data_bytes) / 8))
    # reshape the array to structure of rows, columns and slices
    complex_data = numpy.reshape(complex_data, data_shape).squeeze()

    return MRSData(complex_data,
                   csa_header["RealDwellTime"] * 1e-9,
                   csa_header["ImagingFrequency"],
                   te=csa_header["EchoTime"])
650012
public static InterleavedS8 convert( Planar<GrayS8> input , InterleavedS8 output ) {
		if (output == null) {
			output = new InterleavedS8(input.width, input.height,input.getNumBands());
		} else {
			output.reshape(input.width,input.height,input.getNumBands());
		}

		if( BoofConcurrency.USE_CONCURRENT ) {
			ImplConvertImage_MT.convert(input,output);
		} else {
			ImplConvertImage.convert(input,output);
		}

		return output;
	}
701549
private static WaveletTransform createDefaultShrinkTransform(ImageDataType imageType, int numLevels,
																 double minPixelValue , double maxPixelValue ) {

		WaveletTransform descTran;

		if( !imageType.isInteger()) {
			WaveletDescription<WlCoef_F32> waveletDesc_F32 = FactoryWaveletDaub.daubJ_F32(4);
			descTran = FactoryWaveletTransform.create_F32(waveletDesc_F32,numLevels,
					(float)minPixelValue,(float)maxPixelValue);
		} else {
			WaveletDescription<WlCoef_I32> waveletDesc_I32 = FactoryWaveletDaub.biorthogonal_I32(5, BorderType.REFLECT);
			descTran = FactoryWaveletTransform.create_I(waveletDesc_I32,numLevels,
					(int)minPixelValue,(int)maxPixelValue,
					ImageType.getImageClass(ImageType.Family.GRAY, imageType));
		}
		return descTran;
	}
608723
def _convert_nptype(data_type, data):  # @NoSelf
        '''
        
        '''
        if data_type in (1, 41):
            return np.int8(data).tobytes()
        elif data_type == 2:
            return np.int16(data).tobytes()
        elif data_type == 4:
            return np.int32(data).tobytes()
        elif (data_type == 8) or (data_type == 33):
            return np.int64(data).tobytes()
        elif data_type == 11:
            return np.uint8(data).tobytes()
        elif data_type == 12:
            return np.uint16(data).tobytes()
        elif data_type == 14:
            return np.uint32(data).tobytes()
        elif (data_type == 21) or (data_type == 44):
            return np.float32(data).tobytes()
        elif (data_type == 22) or (data_type == 45) or (data_type == 31):
            return np.float64(data).tobytes()
        elif (data_type == 32):
            return np.complex128(data).tobytes()
        else:
            return data
116602
public Matrix4d invertPerspectiveView(Matrix4x3dc view, Matrix4d dest) {
        double a =  1.0 / (m00 * m11);
        double l = -1.0 / (m23 * m32);
        double pm00 =  m11 * a;
        double pm11 =  m00 * a;
        double pm23 = -m23 * l;
        double pm32 = -m32 * l;
        double pm33 =  m22 * l;
        double vm30 = -view.m00() * view.m30() - view.m01() * view.m31() - view.m02() * view.m32();
        double vm31 = -view.m10() * view.m30() - view.m11() * view.m31() - view.m12() * view.m32();
        double vm32 = -view.m20() * view.m30() - view.m21() * view.m31() - view.m22() * view.m32();
        double nm00 = view.m00() * pm00, nm01 = view.m10() * pm00, nm02 = view.m20() * pm00;
        double nm10 = view.m01() * pm11, nm11 = view.m11() * pm11, nm12 = view.m21() * pm11;
        double nm20 = vm30 * pm23, nm21 = vm31 * pm23, nm22 = vm32 * pm23;
        double nm30 = view.m02() * pm32 + vm30 * pm33;
        double nm31 = view.m12() * pm32 + vm31 * pm33;
        double nm32 = view.m22() * pm32 + vm32 * pm33;
        dest.m00 = nm00;
        dest.m01 = nm01;
        dest.m02 = nm02;
        dest.m03 = 0.0;
        dest.m10 = nm10;
        dest.m11 = nm11;
        dest.m12 = nm12;
        dest.m13 = 0.0;
        dest.m20 = nm20;
        dest.m21 = nm21;
        dest.m22 = nm22;
        dest.m23 = pm23;
        dest.m30 = nm30;
        dest.m31 = nm31;
        dest.m32 = nm32;
        dest.m33 = pm33;
        dest.properties = 0;
        return dest;
    }
666806
def doUnitConversions(self):
        
         # Image information
        _handle = fileutil.openImage(self._filename, mode='readonly', memmap=False)

        # Now convert the SCI array(s) units
        for det in range(1,self._numchips+1):
            chip=self._image[self.scienceExt,det]
            conversionFactor = 1.0
            # add D2IMFILE to outputNames for removal by 'clean()' method later
            if 'D2IMFILE' in _handle[0].header and _handle[0].header['D2IMFILE'] not in ["","N/A"]:
                chip.outputNames['d2imfile'] = _handle[0].header['D2IMFILE']

            if chip._gain is not None:
                """
                # Multiply the values of the sci extension pixels by the gain.
                print "Converting %s[%d] from COUNTS to ELECTRONS"%(self._filename,det)

                # If the exptime is 0 the science image will be zeroed out.
                np.multiply(_handle[self.scienceExt,det].data,chip._gain,_handle[self.scienceExt,det].data)
                chip.data=_handle[self.scienceExt,det].data

                # Set the BUNIT keyword to 'electrons'
                chip._bunit = 'ELECTRONS'
                chip.header.update('BUNIT','ELECTRONS')
                _handle[self.scienceExt,det].header.update('BUNIT','ELECTRONS')

                # Update the PHOTFLAM value
                photflam = _handle[self.scienceExt,det].header['PHOTFLAM']
                _handle[self.scienceExt,det].header.update('PHOTFLAM',(photflam/chip._gain))
                """
                conversionFactor = chip._gain
                chip._effGain = chip._gain #1.
                chip._conversionFactor = conversionFactor #1.

            else:
                msg = "Invalid gain value for data, no conversion done"
                print(msg)
                raise ValueError(msg)

        # Close the files and clean-up
        _handle.close()
        self._effGain = conversionFactor
96022
def dcm2nii(
        dcmpth,
        fimout = '',
        fprefix = 'converted-from-DICOM_',
        fcomment = '',
        outpath = '',
        timestamp = True,
        executable = '',
        force = False,
    ):
    ''' 
    '''

    # skip conversion if the output already exists and not force is selected
    if os.path.isfile(fimout) and not force:
        return fimout

    if executable=='':
        try:
            import resources
            executable = resources.DCM2NIIX
        except:
            raise NameError('e> could not import resources \
                    or find variable DCM2NIIX in resources.py')
    elif not os.path.isfile(executable):
        raise IOError('e> the executable is incorrect!')

    if not os.path.isdir(dcmpth):
        raise IOError('e> the provided DICOM path is not a folder!')

    #> output path
    if outpath=='' and fimout!='' and '/' in fimout:
        opth = os.path.dirname(fimout)
        if opth=='':
            opth = dcmpth
        fimout = os.path.basename(fimout)

    elif outpath=='':
        opth = dcmpth

    else:
        opth = outpath

    create_dir(opth)

    if fimout=='':
        fimout = fprefix
        if timestamp:
            fimout += time_stamp(simple_ascii=True)

    fimout = fimout.split('.nii')[0]


    # convert the DICOM mu-map images to nii
    call([executable, '-f', fimout, '-o', opth, dcmpth])

    fniiout = glob.glob( os.path.join(opth, '*'+fimout+'*.nii*') )

    if fniiout:
        return fniiout[0]
    else:
        raise ValueError('e> could not get the output file!')
105170
def conv2d_trans(ni:int, nf:int, ks:int=2, stride:int=2, padding:int=0, bias=False) -> nn.ConvTranspose2d:
    ""
    return nn.ConvTranspose2d(ni, nf, kernel_size=ks, stride=stride, padding=padding, bias=bias)
314900
def _export_to_vcf(cur):
    
    if float(cur["copyNumber"]) > 2.0:
        svtype = "DUP"
    elif float(cur["copyNumber"]) < 2.0:
        svtype = "DEL"
    else:
        svtype = None
    if svtype:
        info = ["END=%s" % cur["end"], "SVLEN=%s" % (int(cur["end"]) - int(cur["start"])),
                "SVTYPE=%s" % svtype, "CN=%s" % cur["copyNumber"], "PROBES=%s" % cur["depthWindowCount"]]
        return [cur["chromosome"], cur["start"], ".", "N", "<%s>" % svtype, ".", ".",
                ";".join(info), "GT", "0/1"]
838971
def toseries(self):
        
        from thunder.series.series import Series

        if self.mode == 'spark':
            values = self.values.values_to_keys(tuple(range(1, len(self.shape)))).unchunk()

        if self.mode == 'local':
            values = self.values.unchunk()
            values = rollaxis(values, 0, values.ndim)

        return Series(values)
604399
def _zdt_to_nanos(self, zdt):
        """"""
        instant = zdt.toInstant()
        return instant.getNano() + instant.getEpochSecond() * 1000000000
102483
def is_orthogonal_nifti(nifti_file):
    
    nifti_image = nibabel.load(nifti_file)
    affine = nifti_image.affine

    transformed_x = numpy.transpose(numpy.dot(affine, [[1], [0], [0], [0]]))[0][:3]
    transformed_y = numpy.transpose(numpy.dot(affine, [[0], [1], [0], [0]]))[0][:3]
    transformed_z = numpy.transpose(numpy.dot(affine, [[0], [0], [1], [0]]))[0][:3]

    transformed_x /= numpy.linalg.norm(transformed_x)
    transformed_y /= numpy.linalg.norm(transformed_y)
    transformed_z /= numpy.linalg.norm(transformed_z)

    perpendicular = numpy.cross(transformed_x, transformed_y)
    perpendicular /= numpy.linalg.norm(perpendicular)

    if not numpy.allclose(transformed_z, perpendicular, rtol=0.05, atol=0.05) \
            and not numpy.allclose(transformed_z, -perpendicular, rtol=0.05, atol=0.05):
        return False
    return True
839824
function Converter (rgbSpace=workspace.sRGB, whitePoint=illuminant.D65) {
	var primaries = [rgbSpace.r, rgbSpace.g, rgbSpace.b];

	var M_P = matrix.transpose(primaries.map(function (v) {
		var X = v.x / v.y,
		    Y = 1,
		    Z = (1 - v.x - v.y) / v.y;
		return [X, Y, Z];
	}));

	var gamma = rgbSpace.gamma,
	    M_S = matrix.multiply(matrix.inverse(M_P), whitePoint),
	    M_RGB_XYZ = matrix.scalar(M_P, M_S),
	    M_XYZ_RGB = matrix.inverse(M_RGB_XYZ);

	return {
		fromRgb (RGB) {
			return matrix.multiply(M_RGB_XYZ, RGB.map(gamma.decode));
		},
		toRgb (XYZ) {
			return matrix.multiply(M_XYZ_RGB, XYZ).map(gamma.encode);
		},
	};
}
494167
public static int convertToDip(DisplayMetrics displayMetrics, int sizeInPixels) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, sizeInPixels, displayMetrics);
    }