Download quads from a mosaic
328273
def download_quads(name, bbox, rbox, quiet, dest, limit):
    ''''''
    bbox = bbox or rbox
    cl = clientv1()

    dl = downloader.create(cl, mosaic=True)
    output = downloader_output(dl, disable_ansi=quiet)
    output.start()
    try:
        mosaic, = cl.get_mosaic_by_name(name).items_iter(1)
        items = cl.get_quads(mosaic, bbox).items_iter(limit)
    except Exception as ex:
        output.cancel()
        click_exception(ex)
    # invoke the function within an interrupt handler that will shut everything
    # down properly
    handle_interrupt(dl.shutdown, dl.download, items, [], dest)
978497
def _download(self):
        """"""
        # reproject GSSHA grid and get bounds
        min_x, max_x, min_y, max_y = self.gssha_grid.bounds(as_geographic=True)
        if self.era_download_data == 'era5':
            log.info("Downloading ERA5 data ...")
            download_era5_for_gssha(self.lsm_input_folder_path,
                                    self.download_start_datetime,
                                    self.download_end_datetime,
                                    leftlon=min_x-0.5,
                                    rightlon=max_x+0.5,
                                    toplat=max_y+0.5,
                                    bottomlat=min_y-0.5)
        else:
            log.info("Downloading ERA Interim data ...")
            download_interim_for_gssha(self.lsm_input_folder_path,
                                       self.download_start_datetime,
                                       self.download_end_datetime,
                                       leftlon=min_x-1,
                                       rightlon=max_x+1,
                                       toplat=max_y+1,
                                       bottomlat=min_y-1)
1043545
def download_kitchen(split=False):
    
    mesh =  _download_and_read('kitchen.vtk')
    if not split:
        return mesh
    extents = {
        'door' : (27, 27, 14, 18, 0, 11),
        'window1' : (0, 0, 9, 18, 6, 12),
        'window2' : (5, 12, 23, 23, 6, 12),
        'klower1' : (17, 17, 0, 11, 0, 6),
        'klower2' : (19, 19, 0, 11, 0, 6),
        'klower3' : (17, 19, 0, 0, 0, 6),
        'klower4' : (17, 19, 11, 11, 0, 6),
        'klower5' : (17, 19, 0, 11, 0, 0),
        'klower6' : (17, 19, 0, 7, 6, 6),
        'klower7' : (17, 19, 9, 11, 6, 6),
        'hood1' : (17, 17, 0, 11, 11, 16),
        'hood2' : (19, 19, 0, 11, 11, 16),
        'hood3' : (17, 19, 0, 0, 11, 16),
        'hood4' : (17, 19, 11, 11, 11, 16),
        'hood5' : (17, 19, 0, 11, 16, 16),
        'cookingPlate' : (17, 19, 7, 9, 6, 6),
        'furniture' : (17, 19, 7, 9, 11, 11),
    }
    kitchen = vtki.MultiBlock()
    for key, extent in extents.items():
        alg = vtk.vtkStructuredGridGeometryFilter()
        alg.SetInputDataObject(mesh)
        alg.SetExtent(extent)
        alg.Update()
        result = vtki.filters._get_output(alg)
        kitchen[key] = result
    return kitchen
1341591
def quads_to_tris(quads):
    '''
    

    '''
    import numpy as np
    tris = np.empty((2 * len(quads), 3))
    tris[0::2, :] = quads[:, [0, 1, 2]]
    tris[1::2, :] = quads[:, [0, 2, 3]]
    return tris
649276
def _create_affine_siemens_mosaic(dicom_input):
    
    # read dicom series with pds
    dicom_header = dicom_input[0]

    # Create affine matrix (http://nipy.sourceforge.net/nibabel/dicom/dicom_orientation.html#dicom-slice-affine)
    image_orient1 = numpy.array(dicom_header.ImageOrientationPatient)[0:3]
    image_orient2 = numpy.array(dicom_header.ImageOrientationPatient)[3:6]

    normal = numpy.cross(image_orient1, image_orient2)

    delta_r = float(dicom_header.PixelSpacing[0])
    delta_c = float(dicom_header.PixelSpacing[1])

    image_pos = dicom_header.ImagePositionPatient

    delta_s = dicom_header.SpacingBetweenSlices
    return numpy.array(
        [[-image_orient1[0] * delta_c, -image_orient2[0] * delta_r, -delta_s * normal[0], -image_pos[0]],
         [-image_orient1[1] * delta_c, -image_orient2[1] * delta_r, -delta_s * normal[1], -image_pos[1]],
         [image_orient1[2] * delta_c, image_orient2[2] * delta_r, delta_s * normal[2], image_pos[2]],
         [0, 0, 0, 1]])
193840
def download(self, request, **kwargs):
        

        # method check to avoid bad requests
        self.method_check(request, allowed=['get'])

        # create a basic bundle object for self.get_cached_obj_get.
        basic_bundle = self.build_bundle(request=request)

        # using the primary key defined in the url, obtain the tileset
        tileset = self.cached_obj_get(
            bundle=basic_bundle,
            **self.remove_api_resource_names(kwargs))

        filename = helpers.get_tileset_filename(tileset)
        filename = os.path.abspath(filename)
        if os.path.isfile(filename):
            response = serve(request, os.path.basename(filename), os.path.dirname(filename))
            response['Content-Disposition'] = 'attachment; filename="{}"'.format(os.path.basename(filename))
        else:
            response = self.create_response(request, {'status': 'not generated'})
        return response
1355553
def get_tile_geometry(path, origin_espg, tolerance=500):
    

    with rasterio.open(path) as src:

        # Get tile geometry
        b = src.bounds
        tile_shape = Polygon([(b[0], b[1]), (b[2], b[1]), (b[2], b[3]), (b[0], b[3]), (b[0], b[1])])
        tile_geojson = mapping(tile_shape)

        # read first band of the image
        image = src.read(1)

        # create a mask of zero values
        mask = image == 0.

        # generate shapes of the mask
        novalue_shape = shapes(image, mask=mask, transform=src.affine)

        # generate polygons using shapely
        novalue_shape = [Polygon(s['coordinates'][0]) for (s, v) in novalue_shape]

        if novalue_shape:

            # Make sure polygons are united
            # also simplify the resulting polygon
            union = cascaded_union(novalue_shape)

            # generates a geojson
            data_shape = tile_shape.difference(union)

            # If there are multipolygons, select the largest one
            if data_shape.geom_type == 'MultiPolygon':
                areas = {p.area: i for i, p in enumerate(data_shape)}
                largest = max(areas.keys())
                data_shape = data_shape[areas[largest]]

            # if the polygon has interior rings, remove them
            if list(data_shape.interiors):
                data_shape = Polygon(data_shape.exterior.coords)

            data_shape = data_shape.simplify(tolerance, preserve_topology=False)
            data_geojson = mapping(data_shape)

        else:
            data_geojson = tile_geojson

        # convert cooridnates to degrees
        return (to_latlon(tile_geojson, origin_espg), to_latlon(data_geojson, origin_espg))
705441
def bInit( self, vrModel, vrDiffuseTexture ):
        ""
        # create and bind a VAO to hold state for this model
        self.m_glVertArray = glGenVertexArrays(1)
        glBindVertexArray( self.m_glVertArray )
        # Populate a vertex buffer
        self.m_glVertBuffer = glGenBuffers(1)
        glBindBuffer( GL_ARRAY_BUFFER, self.m_glVertBuffer )
        glBufferData( GL_ARRAY_BUFFER, sizeof( openvr.RenderModel_Vertex_t ) * vrModel.unVertexCount, vrModel.rVertexData, GL_STATIC_DRAW )
        # Identify the components in the vertex buffer
        glEnableVertexAttribArray( 0 )
        glVertexAttribPointer( 0, 3, GL_FLOAT, False, sizeof( openvr.RenderModel_Vertex_t ), openvr.RenderModel_Vertex_t.vPosition.offset )
        glEnableVertexAttribArray( 1 )
        glVertexAttribPointer( 1, 3, GL_FLOAT, False, sizeof( openvr.RenderModel_Vertex_t ), openvr.RenderModel_Vertex_t.vNormal.offset )
        glEnableVertexAttribArray( 2 )
        glVertexAttribPointer( 2, 2, GL_FLOAT, False, sizeof( openvr.RenderModel_Vertex_t ), openvr.RenderModel_Vertex_t.rfTextureCoord.offset )
        # Create and populate the index buffer
        self.m_glIndexBuffer = glGenBuffers(1)
        glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, self.m_glIndexBuffer )
        glBufferData( GL_ELEMENT_ARRAY_BUFFER, sizeof( ctypes.c_uint16 ) * vrModel.unTriangleCount * 3, vrModel.rIndexData, GL_STATIC_DRAW )
        glBindVertexArray( 0 )
        # create and populate the texture
        self.m_glTexture = glGenTextures(1)
        glBindTexture( GL_TEXTURE_2D, self.m_glTexture )
        glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, vrDiffuseTexture.unWidth, vrDiffuseTexture.unHeight,
            0, GL_RGBA, GL_UNSIGNED_BYTE, vrDiffuseTexture.rubTextureMapData )
        # If this renders black ask McJohn what's wrong.
        glGenerateMipmap(GL_TEXTURE_2D)
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE )
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE )
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR )
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR )
        fLargest = glGetFloatv( GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT )
        glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, fLargest )
        glBindTexture( GL_TEXTURE_2D, 0 )
        self.m_unVertexCount = vrModel.unTriangleCount * 3
        return True
708495
function Quad(gl)
{
    /*
     * the current WebGL drawing context
     *
     * @member {WebGLRenderingContext}
     */
    this.gl = gl;

//    this.textures = new TextureUvs();

    /**
     * An array of vertices
     *
     * @member {Float32Array}
     */
    this.vertices = new Float32Array([
        0,0,
        200,0,
        200,200,
        0,200
    ]);

    /**
     * The Uvs of the quad
     *
     * @member {Float32Array}
     */
    this.uvs = new Float32Array([
        0,0,
        1,0,
        1,1,
        0,1
    ]);

//    var white = (0xFFFFFF >> 16) + (0xFFFFFF & 0xff00) + ((0xFFFFFF & 0xff) << 16) + (1 * 255 << 24);
    //TODO convert this to a 32 unsigned int array
    /**
     * The color components of the triangles
     *
     * @member {Float32Array}
     */
    this.colors = new Float32Array([
        1,1,1,1,
        1,1,1,1,
        1,1,1,1,
        1,1,1,1
    ]);

    /*
     * @member {Uint16Array} An array containing the indices of the vertices
     */
    this.indices = new Uint16Array([
        0, 1, 2, 0, 3, 2
    ]);

    /*
     * @member {WebGLBuffer} The vertex buffer
     */
    this.vertexBuffer = gl.createBuffer();

    /*
     * @member {WebGLBuffer} The index buffer
     */
    this.indexBuffer = gl.createBuffer();

    gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, (8 + 8 + 16) * 4, gl.DYNAMIC_DRAW);

    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
    gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW);

    this.upload();
}
941834
def _mosaic_to_block(mosaic):
    
    # get the mosaic type
    mosaic_type = _get_mosaic_type(mosaic)

    # get the size of one tile format is 64p*64 or 80*80 or something similar
    matches = re.findall(r'(\d+)\D+(\d+)\D*', str(mosaic[Tag(0x0051, 0x100b)].value))[0]

    ascconv_headers = _get_asconv_headers(mosaic)
    size = [int(matches[0]),
            int(matches[1]),
            int(re.findall(r'sSliceArray\.lSize\s*=\s*(\d+)', ascconv_headers)[0])]

    # get the number of rows and columns
    number_x = int(mosaic.Rows / size[0])
    number_y = int(mosaic.Columns / size[1])

    # recreate 2d slice
    data_2d = mosaic.pixel_array
    # create 3d block
    data_3d = numpy.zeros((size[2], size[1], size[0]), dtype=data_2d.dtype)
    # fill 3d block by taking the correct portions of the slice
    z_index = 0
    for y_index in range(0, number_y):
        if z_index >= size[2]:
            break
        for x_index in range(0, number_x):
            if mosaic_type == MosaicType.ASCENDING:
                data_3d[z_index, :, :] = data_2d[size[1] * y_index:size[1] * (y_index + 1),
                                         size[0] * x_index:size[0] * (x_index + 1)]
            else:
                data_3d[size[2] - (z_index + 1), :, :] = data_2d[size[1] * y_index:size[1] * (y_index + 1),
                                                         size[0] * x_index:size[0] * (x_index + 1)]
            z_index += 1
            if z_index >= size[2]:
                break
    # reorient the block of data
    data_3d = numpy.transpose(data_3d, (2, 1, 0))

    return data_3d
1294024
def get_pixel_skydirs(self):
        

        xpix = np.linspace(0, self.npix[0] - 1., self.npix[0])
        ypix = np.linspace(0, self.npix[1] - 1., self.npix[1])
        xypix = np.meshgrid(xpix, ypix, indexing='ij')
        return SkyCoord.from_pixel(np.ravel(xypix[0]),
                                   np.ravel(xypix[1]), self.wcs)
686893
def tile(self, z, x, y):
        
        logger.debug(_("Download tile %s") % ((z, x, y),))
        # Render each keyword in URL ({s}, {x}, {y}, {z}, {size} ... )
        size = self.tilesize
        s = self.tiles_subdomains[(x + y) % len(self.tiles_subdomains)];
        try:
            url = self.tiles_url.format(**locals())
        except KeyError as e:
            raise DownloadError(_("Unknown keyword %s in URL") % e)

        logger.debug(_("Retrieve tile at %s") % url)
        r = DOWNLOAD_RETRIES
        sleeptime = 1
        while r > 0:
            try:
                request = requests.get(url, headers=self.headers)
                if request.status_code == 200:
                    return request.content
                raise DownloadError(_("Status code : %s, url : %s") % (request.status_code, url))
            except requests.exceptions.ConnectionError as e:
                logger.debug(_("Download error, retry (%s left). (%s)") % (r, e))
                r -= 1
                time.sleep(sleeptime)
                # progressivly sleep longer to wait for this tile
                if (sleeptime <= 10) and (r % 2 == 0):
                    sleeptime += 1  # increase wait
        raise DownloadError(_("Cannot download URL %s") % url)
575617
def mosaic_info(name, pretty):
    ''''''
    cl = clientv1()
    echo_json_response(call_and_wrap(cl.get_mosaic_by_name, name), pretty)
222403
def quad_contributions(name, quad, pretty):
    ''''''
    cl = clientv1()
    mosaic, = cl.get_mosaic_by_name(name).items_iter(1)
    quad = cl.get_quad_by_id(mosaic, quad).get()
    response = call_and_wrap(cl.get_quad_contributions, quad)
    echo_json_response(response, pretty)
910250
function tileToPixelCoords(q, r, v) {
         var x, y;
         var ret = v || new me.Vector2d();

         if (this.staggeraxis === "x") {
           //flat top
           x = q * this.columnwidth;

           if (this.staggerindex === "odd") {
             y = r * (this.tileheight + this.sidelengthy);
             y = y + this.rowheight * (q & 1);
           } else {
             y = r * (this.tileheight + this.sidelengthy);
             y = y + this.rowheight * (1 - (q & 1));
           }
         } else {
           //pointy top
           y = r * this.rowheight;

           if (this.staggerindex === "odd") {
             x = q * (this.tilewidth + this.sidelengthx);
             x = x + this.columnwidth * (r & 1);
           } else {
             x = q * (this.tilewidth + this.sidelengthx);
             x = x + this.columnwidth * (1 - (r & 1));
           }
         }

         return ret.set(x, y);
       }
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}
737286
def copy_dependency_images(tile):
    """"""

    env = Environment(tools=[])

    outputbase = os.path.join('build', 'output')
    depbase = os.path.join('build', 'deps')
    for dep in tile.dependencies:
        depdir = os.path.join(depbase, dep['unique_id'])
        outputdir = os.path.join(outputbase)

        deptile = IOTile(depdir)

        for image in deptile.find_products('firmware_image'):
            name = os.path.basename(image)
            input_path = os.path.join(depdir, name)
            output_path = os.path.join(outputdir, name)
            env.Command([output_path], [input_path], Copy("$TARGET", "$SOURCE"))