write_mtl: When True and mesh has a texture, includes a mtllib
      reference in the .obj and writes a .mtl alongside.
482606
def _dump(f, obj, flip_faces=False, ungroup=False, comments=None, split_normals=False, write_mtl=True): # pylint: disable=redefined-outer-name
    '''
    

    '''
    import os
    import numpy as np
    from baiji import s3

    ff = -1 if flip_faces else 1
    def write_face_to_obj_file(obj, faces, face_index, obj_file):
        vertex_indices = faces[face_index][::ff] + 1

        write_normals = obj.fn is not None or (obj.vn is not None and obj.vn.shape == obj.v.shape)
        write_texture = obj.ft is not None and obj.vt is not None

        if write_normals and obj.fn is not None:
            normal_indices = obj.fn[face_index][::ff] + 1
            assert len(normal_indices) == len(vertex_indices)
        elif write_normals: # unspecified fn but per-vertex normals, assume ordering is same as for v
            normal_indices = faces[face_index][::ff] + 1

        if write_texture:
            texture_indices = obj.ft[face_index][::ff] + 1
            assert len(texture_indices) == len(vertex_indices)

        # Valid obj face lines are: v, v/vt, v//vn, v/vt/vn
        if write_normals and write_texture:
            pattern = '%d/%d/%d'
            value = tuple(np.array([vertex_indices, texture_indices, normal_indices]).T.flatten())
        elif write_normals:
            pattern = '%d//%d'
            value = tuple(np.array([vertex_indices, normal_indices]).T.flatten())
        elif write_texture:
            pattern = '%d/%d'
            value = tuple(np.array([vertex_indices, texture_indices]).T.flatten())
        else:
            pattern = '%d'
            value = tuple(vertex_indices)
        obj_file.write(('f ' + ' '.join([pattern]*len(vertex_indices)) + '\n') % value)

    if comments != None:
        if isinstance(comments, basestring):
            comments = [comments]
        for comment in comments:
            for line in comment.split("\n"):
                f.write("# %s\n" % line)

    if write_mtl and hasattr(obj, 'texture_filepath') and obj.texture_filepath is not None:
        save_to = s3.path.dirname(f.name)
        mtl_name = os.path.splitext(s3.path.basename(f.name))[0]
        mtl_filename = mtl_name + '.mtl'
        f.write('mtllib %s\n' % mtl_filename)
        f.write('usemtl %s\n' % mtl_name)
        texture_filename = mtl_name + os.path.splitext(obj.texture_filepath)[1]
        if not s3.exists(s3.path.join(save_to, texture_filename)):
            s3.cp(obj.texture_filepath, s3.path.join(save_to, texture_filename))
        obj.write_mtl(s3.path.join(save_to, mtl_filename), mtl_name, texture_filename)

    if obj.vc is not None:
        for r, c in zip(obj.v, obj.vc):
            f.write('v %f %f %f %f %f %f\n' % (r[0], r[1], r[2], c[0], c[1], c[2]))
    elif obj.v is not None:
        for r in obj.v:
            f.write('v %f %f %f\n' % (r[0], r[1], r[2]))

    if obj.vn is not None:
        if split_normals:
            for vn_idx in obj.fn:
                r = obj.vn[vn_idx[0]]
                f.write('vn %f %f %f\n' % (r[0], r[1], r[2]))
                r = obj.vn[vn_idx[1]]
                f.write('vn %f %f %f\n' % (r[0], r[1], r[2]))
                r = obj.vn[vn_idx[2]]
                f.write('vn %f %f %f\n' % (r[0], r[1], r[2]))
        else:
            for r in obj.vn:
                f.write('vn %f %f %f\n' % (r[0], r[1], r[2]))

    if obj.ft is not None and obj.vt is not None:
        for r in obj.vt:
            if len(r) == 3:
                f.write('vt %f %f %f\n' % (r[0], r[1], r[2]))
            else:
                f.write('vt %f %f\n' % (r[0], r[1]))
    if obj.f4 is not None:
        faces = obj.f4
    elif obj.f is not None:
        faces = obj.f
    else:
        faces = None
    if obj.segm is not None and not ungroup:
        if faces is not None:
            # An array of strings.
            group_names = np.array(obj.segm.keys())

            # A 2d array of booleans indicating which face is in which group.
            group_mask = np.zeros((len(group_names), len(faces)), dtype=bool)
            for i, segm_faces in enumerate(obj.segm.itervalues()):
                group_mask[i][segm_faces] = True

            # In an OBJ file, "g" changes the current state. This is a slice of
            # group_mask that represents the current state.
            current_group_mask = np.zeros((len(group_names),), dtype=bool)

            for face_index in range(len(faces)):
                # If the group has changed from the previous face, write the
                # group entry.
                this_group_mask = group_mask[:, face_index]
                if any(current_group_mask != this_group_mask):
                    current_group_mask = this_group_mask
                    f.write('g %s\n' % ' '.join(group_names[current_group_mask]))

                write_face_to_obj_file(obj, faces, face_index, f)
    else:
        if faces is not None:
            for face_index in range(len(faces)):
                write_face_to_obj_file(obj, faces, face_index, f)
682439
def writeFace(self, val, what='f'):
        
        # OBJ counts from 1
        val = [v + 1 for v in val]
        # Make string
        if self._hasValues and self._hasNormals:
            val = ' '.join(['%i/%i/%i' % (v, v, v) for v in val])
        elif self._hasNormals:
            val = ' '.join(['%i//%i' % (v, v) for v in val])
        elif self._hasValues:
            val = ' '.join(['%i/%i' % (v, v) for v in val])
        else:
            val = ' '.join(['%i' % v for v in val])
        # Write line
        self.writeLine('%s %s' % (what, val))
787495
def get_mesh(self, body_name, **kwargs):
        """"""
        body = self.bodies[body_name]
        vertices = body['v']
        normals = body['vn'] if 'vn' in body else None
        texcoords = body['vt'] if 'vt' in body else None
        mesh = Mesh.from_incomplete_data(vertices=vertices, normals=normals, texcoords=texcoords, **kwargs)

        uniforms = kwargs['uniforms'] if 'uniforms' in kwargs else {}
        if 'material' in body:
            material_props = {self.material_property_map[key]: value for key, value in iteritems(body['material'])}
            for key, value in iteritems(material_props):
                if isinstance(value, str):
                    if key == 'map_Kd':
                        if not value in self.textures:
                            self.textures[value] = Texture.from_image(value)
                        mesh.textures.append(self.textures[value])
                    else:
                        setattr(mesh, key, value)
                elif hasattr(value, '__len__'):  # iterable materials
                    mesh.uniforms[key] = value
                elif key in ['d', 'illum']:  # integer materials
                    mesh.uniforms[key] = value
                elif key in ['spec_weight', 'Ni']:  # float materials: should be specially converted to float if not already done.
                    mesh.uniforms[key] = float(value)
                else:
                    print('Warning: Not applying uniform {}: {}'.format(key, value))
        return mesh
519662
def draw360_to_texture(self, cubetexture, **kwargs):
        

        assert self.camera.projection.aspect == 1. and self.camera.projection.fov_y == 90  # todo: fix aspect property, which currently reads from viewport.
        if not isinstance(cubetexture, TextureCube):
            raise ValueError("Must render to TextureCube")

        # for face, rotation in enumerate([[180, 90, 0], [180, -90, 0], [90, 0, 0], [-90, 0, 0], [180, 0, 0], [0, 0, 180]]):
        old_rotation = self.camera.rotation
        self.camera.rotation = self.camera.rotation.to_euler(units='deg')
        for face, rotation in enumerate([[180, -90, 0], [180, 90, 0], [90, 0, 0], [-90, 0, 0], [180, 0, 0], [0, 0, 180]]):  #first 2 switched
            self.camera.rotation.xyz = rotation
            cubetexture.attach_to_fbo(face)
            self.draw(**kwargs)
        self.camera.rotation = old_rotation
1273969
def write_frame(self):
        
        if not hasattr(self, 'mwriter'):
            raise AssertionError('This plotter has not opened a movie or GIF file.')
        self.mwriter.append_data(self.image)
702201
def save(obj=None, m2m_data=None):
    
    m2m_data = {} if m2m_data is None else m2m_data
    obj.save_base(raw=True)
    for attr, values in m2m_data.items():
        for value in values:
            getattr(obj, attr).add(value)
796233
function updateTexture2D(ctx, texture, opts) {
  // checkProps(allowedProps, opts)

  const gl = ctx.gl
  const PixelFormat = ctx.PixelFormat

  let data = null
  let width = opts.width
  let height = opts.height
  let lod = 0
  let flipY = orValue(opts.flipY, orValue(texture.flipY, false))
  let target = opts.target || texture.target
  let pixelFormat =
    opts.pixelFormat || texture.pixelFormat || ctx.PixelFormat.RGBA8
  let encoding = opts.encoding || texture.encoding || ctx.Encoding.Linear
  let min = opts.min || texture.min || gl.NEAREST
  let mag = opts.mag || texture.mag || gl.NEAREST
  let wrapS =
    opts.wrapS || texture.wrapS || opts.wrap || texture.wrap || gl.CLAMP_TO_EDGE
  let wrapT =
    opts.wrapT || texture.wrapT || opts.wrap || texture.wrap || gl.CLAMP_TO_EDGE
  let aniso = opts.aniso || texture.aniso || 0
  let premultiplayAlpha = orValue(
    opts.premultiplayAlpha,
    orValue(texture.premultiplayAlpha, false)
  )
  let internalFormat
  let type
  let format

  var anisoExt = gl.getExtension('EXT_texture_filter_anisotropic')

  const textureUnit = 0
  gl.activeTexture(gl.TEXTURE0 + textureUnit)
  gl.bindTexture(texture.target, texture.handle)
  ctx.state.activeTextures[textureUnit] = texture

  gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY)
  gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, premultiplayAlpha)
  gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, mag)
  gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, min)
  gl.texParameteri(target, gl.TEXTURE_WRAP_S, wrapS)
  gl.texParameteri(target, gl.TEXTURE_WRAP_T, wrapT)
  if (anisoExt && aniso > 0) {
    gl.texParameterf(target, anisoExt.TEXTURE_MAX_ANISOTROPY_EXT, aniso)
  }

  // just an image
  // opts = HTMLImage

  // image with flags
  // opts = { data: HTMLImage, flipY: Boolean }

  // pixel data
  // opts = { data: Array, width: Number, height: Number, flipY: Boolean }

  // pixel data with flags
  // opts = { data: { data: Array, width: Number, height: Number }, flipY: Boolean },

  // array of images for cubemaps (and array textures in webgl2)
  // opts = { data: [ HTMLImage, ... ], width: Number, height: Number, flipY: Boolean }

  // array of pixel data for cubemaps (and array texture in webgl2)
  // opts = { data: [ { data: Array, width: Number, height: Number }, ..], flipY: Boolean }

  const img = opts.data ? opts.data : opts
  if (img && img.nodeName) {
    assert(
      img instanceof window.HTMLImageElement ||
        img instanceof window.HTMLVideoElement ||
        img instanceof window.HTMLCanvasElement,
      'Texture2D.update opts has to be Image, Canvas or Video element'
    )
    width = img.width || img.videoHeight
    height = img.height || img.videoHeight
    internalFormat = gl.RGBA
    format = gl.RGBA
    type = gl.UNSIGNED_BYTE
    gl.texImage2D(target, lod, internalFormat, format, type, img)
    texture.width = width
    texture.height = height
  } else if (typeof opts === 'object') {
    assert(
      !data ||
        Array.isArray(opts.data) ||
        opts.data instanceof Uint8Array ||
        opts.data instanceof Float32Array,
      'Texture2D.update opts.data has to be null or an Array, Uint8Array or Float32Array'
    )

    data = opts.data ? opts.data.data || opts.data : null

    if (!opts.width && data && data.width) width = data.width
    if (!opts.height && data && data.height) width = data.height

    assert(
      !data || (width !== undefined && height !== undefined),
      'Texture2D.update opts.width and opts.height are required when providing opts.data'
    )

    if (pixelFormat === PixelFormat.Depth) {
      format = gl.DEPTH_COMPONENT
      internalFormat = gl.DEPTH_COMPONENT
      type = gl.UNSIGNED_SHORT
    } else if (pixelFormat === PixelFormat.RGBA8) {
      format = gl.RGBA
      internalFormat = gl.RGBA
      type = gl.UNSIGNED_BYTE
    } else if (pixelFormat === PixelFormat.RGBA32F) {
      format = gl.RGBA
      internalFormat = gl.RGBA
      type = gl.FLOAT
    } else if (pixelFormat === PixelFormat.RGBA16F) {
      format = gl.RGBA
      internalFormat = gl.RGBA
      type = gl.HALF_FLOAT
    } else if (pixelFormat === PixelFormat.R32F) {
      format = gl.ALPHA
      internalFormat = gl.ALPHA
      type = gl.FLOAT
    } else if (pixelFormat) {
      assert.fail(`Unknown texture pixel format: ${opts.format}`)
    }

    if (target === gl.TEXTURE_2D) {
      if (Array.isArray(data)) {
        if (type === gl.UNSIGNED_BYTE) {
          data = new Uint8Array(data)
        } else if (type === gl.FLOAT) {
          data = new Float32Array(data)
        } else if (type === gl.HALF_FLOAT) {
          data = new Float32Array(data)
        } else {
          assert.fail(`Unknown texture data type: ${type}`)
        }
      }
      if (width && height) {
        gl.texImage2D(
          target,
          lod,
          internalFormat,
          width,
          height,
          0,
          format,
          type,
          data
        )
        texture.width = width
        texture.height = height
      }
    } else if (target === gl.TEXTURE_CUBE_MAP) {
      assert(
        !data || (Array.isArray(data) && data.length === 6),
        'TextureCube requires data for 6 faces'
      )
      for (let i = 0; i < 6; i++) {
        let faceData = data ? data[i].data || data[i] : null
        const faceTarget = gl.TEXTURE_CUBE_MAP_POSITIVE_X + i
        if (Array.isArray(faceData)) {
          if (type === gl.UNSIGNED_BYTE) {
            faceData = new Uint8Array(faceData)
          } else if (type === gl.FLOAT) {
            faceData = new Float32Array(data)
          } else {
            assert.fail(`Unknown texture data type: ${type}`)
          }
          gl.texImage2D(
            faceTarget,
            lod,
            internalFormat,
            width,
            height,
            0,
            format,
            type,
            faceData
          )
        } else if (faceData && faceData.nodeName) {
          gl.texImage2D(faceTarget, lod, internalFormat, format, type, faceData)
        } else {
          gl.texImage2D(
            faceTarget,
            lod,
            internalFormat,
            width,
            height,
            0,
            format,
            type,
            faceData
          )
        }
        texture.width = width
        texture.height = height
      }
    }
  } else {
    // TODO: should i assert of throw new Error(msg)?
    assert.fail('Texture2D.update opts has to be a HTMLElement or Object')
  }

  if (opts.mipmap) {
    gl.generateMipmap(texture.target)
  }

  texture.target = target
  texture.pixelFormat = pixelFormat
  texture.encoding = encoding
  texture.min = min
  texture.mag = mag
  texture.wrapS = wrapS
  texture.wrapT = wrapT
  texture.format = format
  texture.flipY = flipY
  texture.internalFormat = internalFormat
  texture.type = type
  texture.info = ''
  texture.info += Object.keys(ctx.PixelFormat).find(
    (key) => ctx.PixelFormat[key] === pixelFormat
  )
  texture.info += '_'
  texture.info += Object.keys(ctx.Encoding).find(
    (key) => ctx.Encoding[key] === encoding
  )

  return texture
}
491778
def write(fn, a, **kwargs):
    
    ext = fn[fn.rfind('.'):].split('@')
    if ext[0] == '.out' or ext[0] == '.dat':
        return write_atoms(fn, a)
    elif ext[0] == '.lammps':
        return write_lammps_data(fn, a, velocities=True, **kwargs)
    elif ext[0] == '.nc':
        return NetCDFTrajectory(fn, 'w').write(a)
    else:
        return ase.io.write(fn, a, **kwargs)
937478
def write(models, csvout, rulelist, write_header, base=None, logger=logging):
    '''
    
    '''
    properties = [ k for (k, v) in rulelist ]
    numprops = len(properties)
    headers = [ v for (k, v) in rulelist ]
    if write_header:
        csvout.writerow(['id', 'type'] + headers)

    rules = { k: v for (k, v) in rulelist }

    if not isinstance(models, list): models = [models]
    for m in models:
        mapped = omap(m)
        for o, props in mapped.items():
            rtypes = list(map(operator.itemgetter(0), props.get(RDF_TYPE_REL, [])))
            if not rtypes: continue
            #print('RES TYPES:', rtypes)
            row = [o, fromlist(rtypes)] + [None] * numprops
            for ix, p in enumerate(properties):
                v = list(map(operator.itemgetter(0), props.get(p, [])))
                if v:
                    row[ix + 2] = fromlist(v)
                    csvout.writerow(row)

    return
282257
def write(self, learn:Learner, trn_batch:Tuple, val_batch:Tuple, iteration:int, tbwriter:SummaryWriter)->None:
        ""
        self._write_for_dstype(learn=learn, batch=val_batch, iteration=iteration, tbwriter=tbwriter, ds_type=DatasetType.Valid)
        self._write_for_dstype(learn=learn, batch=trn_batch, iteration=iteration, tbwriter=tbwriter, ds_type=DatasetType.Train)
616990
function LGraphTextureDepthRange() {
            this.addInput("Texture", "Texture");
            this.addInput("Distance", "number");
            this.addInput("Range", "number");
            this.addOutput("Texture", "Texture");
            this.properties = {
                distance: 100,
                range: 50,
                only_depth: false,
                high_precision: false
            };
            this._uniforms = {
                u_texture: 0,
                u_distance: 100,
                u_range: 50,
                u_camera_planes: null
            };
        }
1246398
def _dump(f, mesh):
    '''
    
    '''
    dae = mesh_to_collada(mesh)
    dae.write(f.name)
685702
def writeObject(self, obj, output, setReferencePosition=False):
        
        def proc_variable_length(format, length):
            result = b''
            if length > 0b1110:
                result += pack('!B', (format << 4) | 0b1111)
                result = self.writeObject(length, result)
            else:
                result += pack('!B', (format << 4) | length)
            return result
        
        def timedelta_total_seconds(td):
            # Shim for Python 2.6 compatibility, which doesn't have total_seconds.
            # Make one argument a float to ensure the right calculation.
            return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10.0**6) / 10.0**6
       
        if setReferencePosition:
            self.referencePositions[obj] = len(output)
        
        if obj is None:
            output += pack('!B', 0b00000000)
        elif isinstance(obj, BoolWrapper):
            if obj.value is False:
                output += pack('!B', 0b00001000)
            else:
                output += pack('!B', 0b00001001)
        elif isinstance(obj, Uid):
            size = self.intSize(obj.integer)
            output += pack('!B', (0b1000 << 4) | size - 1)
            output += self.binaryInt(obj.integer)
        elif isinstance(obj, (int, long)):
            byteSize = self.intSize(obj)
            root = math.log(byteSize, 2)
            output += pack('!B', (0b0001 << 4) | int(root))
            output += self.binaryInt(obj, as_number=True)
        elif isinstance(obj, FloatWrapper):
            # just use doubles
            output += pack('!B', (0b0010 << 4) | 3)
            output += self.binaryReal(obj)
        elif isinstance(obj, datetime.datetime):
            try:
                timestamp = (obj - apple_reference_date).total_seconds()
            except AttributeError:
                timestamp = timedelta_total_seconds(obj - apple_reference_date)
            output += pack('!B', 0b00110011)
            output += pack('!d', float(timestamp))
        elif isinstance(obj, Data):
            output += proc_variable_length(0b0100, len(obj))
            output += obj
        elif isinstance(obj, StringWrapper):
            output += proc_variable_length(obj.encodingMarker, len(obj))
            output += obj.encodedValue
        elif isinstance(obj, bytes):
            output += proc_variable_length(0b0101, len(obj))
            output += obj
        elif isinstance(obj, HashableWrapper):
            obj = obj.value
            if isinstance(obj, (set, list, tuple)):
                if isinstance(obj, set):
                    output += proc_variable_length(0b1100, len(obj))
                else:
                    output += proc_variable_length(0b1010, len(obj))
            
                objectsToWrite = []
                for objRef in sorted(obj) if isinstance(obj, set) else obj:
                    (isNew, output) = self.writeObjectReference(objRef, output)
                    if isNew:
                        objectsToWrite.append(objRef)
                for objRef in objectsToWrite:
                    output = self.writeObject(objRef, output, setReferencePosition=True)
            elif isinstance(obj, dict):
                output += proc_variable_length(0b1101, len(obj))
                keys = []
                values = []
                objectsToWrite = []
                for key, value in sorted(iteritems(obj)):
                    keys.append(key)
                    values.append(value)
                for key in keys:
                    (isNew, output) = self.writeObjectReference(key, output)
                    if isNew:
                        objectsToWrite.append(key)
                for value in values:
                    (isNew, output) = self.writeObjectReference(value, output)
                    if isNew:
                        objectsToWrite.append(value)
                for objRef in objectsToWrite:
                    output = self.writeObject(objRef, output, setReferencePosition=True)
        return output
882416
def write(obj, filepath):
    
    if not isinstance(obj, Multitrack):
        raise TypeError("Support only `pypianoroll.Multitrack` class objects")
    obj.write(filepath)
1188611
function LGraphTextureBlur() {
            this.addInput("Texture", "Texture");
            this.addInput("Iterations", "number");
            this.addInput("Intensity", "number");
            this.addOutput("Blurred", "Texture");
            this.properties = {
                intensity: 1,
                iterations: 1,
                preserve_aspect: false,
                scale: [1, 1],
                precision: LGraphTexture.DEFAULT
            };
        }
339334
def write_object(self, obj, parent=None):
        
        # Transform object
        for transformer in self.object_transformers:
            tmp_object = transformer.transform(obj)
            if tmp_object is not obj:
                obj = tmp_object
                break

        self._writeStruct(">B", 1, (self.TC_OBJECT,))
        cls = obj.get_class()
        self.write_classdesc(cls)

        # Add reference
        self.references.append([])
        logging.debug(
            "*** Adding ref 0x%X for object %s",
            len(self.references) - 1 + self.BASE_REFERENCE_IDX,
            obj,
        )

        all_names = collections.deque()
        all_types = collections.deque()
        tmpcls = cls
        while tmpcls:
            all_names.extendleft(reversed(tmpcls.fields_names))
            all_types.extendleft(reversed(tmpcls.fields_types))
            tmpcls = tmpcls.superclass
        del tmpcls

        logging.debug("<=> Field names: %s", all_names)
        logging.debug("<=> Field types: %s", all_types)

        for field_name, field_type in zip(all_names, all_types):
            try:
                logging.debug(
                    "Writing field %s (%s): %s",
                    field_name,
                    field_type,
                    getattr(obj, field_name),
                )
                self._write_value(field_type, getattr(obj, field_name))
            except AttributeError as ex:
                log_error(
                    "No attribute {0} for object {1}\nDir: {2}".format(
                        ex, repr(obj), dir(obj)
                    )
                )
                raise
        del all_names, all_types

        if (
            cls.flags & self.SC_SERIALIZABLE
            and cls.flags & self.SC_WRITE_METHOD
            or cls.flags & self.SC_EXTERNALIZABLE
            and cls.flags & self.SC_BLOCK_DATA
        ):
            for annotation in obj.annotations:
                log_debug(
                    "Write annotation {0} for {1}".format(repr(annotation), repr(obj))
                )
                if annotation is None:
                    self.write_null()
                else:
                    self.writeObject(annotation)
            self._writeStruct(">B", 1, (self.TC_ENDBLOCKDATA,))
1247351
def write(filename, mesh, write_binary=False):
    
    assert not write_binary
    if mesh.points.shape[1] == 2:
        logging.warning(
            "mdpa requires 3D points, but 2D points given. "
            "Appending 0 third component."
        )
        mesh.points = numpy.column_stack(
            [mesh.points[:, 0], mesh.points[:, 1], numpy.zeros(mesh.points.shape[0])]
        )

    # Kratos cells are mostly ordered like VTK, with a few exceptions:
    cells = mesh.cells.copy()
    if "hexahedron20" in cells:
        cells["hexahedron20"] = cells["hexahedron20"][
            :, [0, 1, 2, 3, 4, 5, 6, 7, 8, 11, 10, 9, 16, 17, 18, 19, 12, 15, 14, 13]
        ]
    if "hexahedron27" in cells:
        cells["hexahedron27"] = cells["hexahedron27"][
            :,
            [
                0,
                1,
                2,
                3,
                4,
                5,
                6,
                7,
                8,
                11,
                10,
                9,
                16,
                17,
                18,
                19,
                12,
                15,
                14,
                13,
                22,
                24,
                21,
                23,
                20,
                25,
                26,
            ],
        ]

    with open(filename, "wb") as fh:
        # Write some additional info
        fh.write(("Begin ModelPartData\n").encode("utf-8"))
        fh.write(("//  VARIABLE_NAME value\n").encode("utf-8"))
        fh.write(("End ModelPartData\n\n").encode("utf-8"))
        fh.write(("Begin Properties 0\n").encode("utf-8"))
        fh.write(("End Properties\n\n").encode("utf-8"))

        # Split the cell data: gmsh:physical and gmsh:geometrical are tags, the
        # rest is actual cell data.
        tag_data = {}
        other_data = {}
        for cell_type, a in mesh.cell_data.items():
            tag_data[cell_type] = {}
            other_data[cell_type] = {}
            for key, data in a.items():
                if key in ["gmsh:physical", "gmsh:geometrical"]:
                    tag_data[cell_type][key] = data.astype(numpy.int32)
                else:
                    other_data[cell_type][key] = data

        # We identity which dimension are we
        dimension = 2
        for cell_type in cells.keys():
            name_elem = _meshio_to_mdpa_type[cell_type]
            if local_dimension_types[name_elem] == 3:
                dimension = 3
                break

        # We identify the entities
        _write_nodes(fh, mesh.points, write_binary)
        _write_elements_and_conditions(fh, cells, tag_data, write_binary, dimension)
        for name, dat in mesh.point_data.items():
            _write_data(fh, "NodalData", name, dat, write_binary)
        cell_data_raw = raw_from_cell_data(other_data)
        for (
            name,
            dat,
        ) in (
            cell_data_raw.items()
        ):  # NOTE: We will assume always when writing that the components are elements (for now)
            _write_data(fh, "ElementalData", name, dat, write_binary)

    return