Write an array of bvecs to a bvec file

    :param bvecs: array with the vectors
    :param bvec_file: filepath to write to
18333
def write_bvec_file(bvecs, bvec_file):
    
    if bvec_file is None:
        return
    logger.info('Saving BVEC file: %s' % bvec_file)
    with open(bvec_file, 'w') as text_file:
        # Map a dicection to string join them using a space and write to the file
        text_file.write('%s\n' % ' '.join(map(str, bvecs[:, 0])))
        text_file.write('%s\n' % ' '.join(map(str, bvecs[:, 1])))
        text_file.write('%s\n' % ' '.join(map(str, bvecs[:, 2])))
449447
def _append_array(self, value, _file):
        
        _labs = ' ['
        _file.write(_labs)

        self._tctr += 1

        for _item in value:
            _cmma = ',' if self._vctr[self._tctr] else ''
            _file.write(_cmma)

            self._vctr[self._tctr] += 1

            _item = self.object_hook(_item)
            _type = type(_item).__name__
            _MAGIC_TYPES[_type](self, _item, _file)

        self._vctr[self._tctr] = 0
        self._tctr -= 1

        _labs = ' ]'
        _file.write(_labs)
1169623
def write
      begin
        buf = [ @flags, @length, @id, @crc].pack(FORMAT)
        crc = Zlib.crc32(buf, 0)
        @file.seek(@addr)
        @file.write(buf + [ crc ].pack('L'))
      rescue IOError => e
        PEROBS.log.fatal "Cannot write blob header into flat file DB: " +
          e.message
      end
    end
751962
def write(filename, mesh, file_format=None, **kwargs):
    
    if not file_format:
        # deduce file format from extension
        file_format = _filetype_from_filename(filename)

    # check cells for sanity
    for key, value in mesh.cells.items():
        if key[:7] == "polygon":
            assert value.shape[1] == int(key[7:])
        else:
            assert value.shape[1] == num_nodes_per_cell[key]

    try:
        interface, args, default_kwargs = _writer_map[file_format]
    except KeyError:
        raise KeyError(
            "Unknown format '{}'. Pick one of {}".format(
                file_format, sorted(list(_writer_map.keys()))
            )
        )

    # Build kwargs
    _kwargs = default_kwargs.copy()
    _kwargs.update(kwargs)

    # Write
    return interface.write(filename, mesh, *args, **_kwargs)
620704
public static <T extends SequenceElement> void writeSequenceVectors(@NonNull SequenceVectors<T> vectors,
                                                                        @NonNull SequenceElementFactory<T> factory, @NonNull OutputStream stream) throws IOException {
        WeightLookupTable<T> lookupTable = vectors.getLookupTable();
        VocabCache<T> vocabCache = vectors.getVocab();

        try (PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream, StandardCharsets.UTF_8)))) {

            // at first line we save VectorsConfiguration
            writer.write(vectors.getConfiguration().toEncodedJson());

            // now we have elements one by one
            for (int x = 0; x < vocabCache.numWords(); x++) {
                T element = vocabCache.elementAtIndex(x);
                String json = factory.serialize(element);
                INDArray d = Nd4j.create(1);
                double[] vector = lookupTable.vector(element.getLabel()).dup().data().asDouble();
                ElementPair pair = new ElementPair(json, vector);
                writer.println(pair.toEncodedJson());
                writer.flush();
            }
        }
    }
402024
def _get_bvals_bvecs(grouped_dicoms):
    
    # loop over all timepoints and create a list with all bvals and bvecs
    bvals = numpy.zeros([len(grouped_dicoms)], dtype=numpy.int32)
    bvecs = numpy.zeros([len(grouped_dicoms), 3])

    for group_index in range(0, len(grouped_dicoms)):
        dicom_ = grouped_dicoms[group_index][0]
        # 0019:10bb: Diffusion X
        # 0019:10bc: Diffusion Y
        # 0019:10bd: Diffusion Z
        # 0043:1039: B-values (4 values, 1st value is actual B value)

        # bval can be stored both in string as number format in dicom so implement both
        # some workarounds needed for implicit transfer syntax to work
        if isinstance(dicom_[Tag(0x0043, 0x1039)].value, string_types):  # this works for python2.7
            original_bval = float(dicom_[Tag(0x0043, 0x1039)].value.split('\\')[0])
        elif isinstance(dicom_[Tag(0x0043, 0x1039)].value, bytes):  # this works for python3.o
            original_bval = float(dicom_[Tag(0x0043, 0x1039)].value.decode("utf-8").split('\\')[0])
        else:
            original_bval = dicom_[Tag(0x0043, 0x1039)][0]
        original_bvec = numpy.array([0, 0, 0], dtype=numpy.float)
        original_bvec[0] = -float(dicom_[Tag(0x0019, 0x10bb)].value)  # invert based upon mricron output
        original_bvec[1] = float(dicom_[Tag(0x0019, 0x10bc)].value)
        original_bvec[2] = float(dicom_[Tag(0x0019, 0x10bd)].value)

        # Add calculated B Value
        if original_bval != 0:  # only normalize if there is a value
            corrected_bval = original_bval * pow(numpy.linalg.norm(original_bvec), 2)
            if numpy.linalg.norm(original_bvec) != 0:
                normalized_bvec = original_bvec / numpy.linalg.norm(original_bvec)
            else:
                normalized_bvec = original_bvec
        else:
            corrected_bval = original_bval
            normalized_bvec = original_bvec

        bvals[group_index] = int(round(corrected_bval))  # we want the original numbers back as in the protocol
        bvecs[group_index, :] = normalized_bvec

    return bvals, bvecs
950734
public static void writeWord2VecModel(Word2Vec vectors, OutputStream stream) throws IOException {
        ZipOutputStream zipfile = new ZipOutputStream(new BufferedOutputStream(new CloseShieldOutputStream(stream)));

        ZipEntry syn0 = new ZipEntry("syn0.txt");
        zipfile.putNextEntry(syn0);

        // writing out syn0
        File tempFileSyn0 = DL4JFileUtils.createTempFile("word2vec", "0");
        File tempFileSyn1 = DL4JFileUtils.createTempFile("word2vec", "1");
        File tempFileSyn1Neg = DL4JFileUtils.createTempFile("word2vec", "n");
        File tempFileCodes = DL4JFileUtils.createTempFile("word2vec", "h");
        File tempFileHuffman = DL4JFileUtils.createTempFile("word2vec", "h");
        File tempFileFreqs = DL4JFileUtils.createTempFile("word2vec", "f");
        tempFileSyn0.deleteOnExit();
        tempFileSyn1.deleteOnExit();
        tempFileSyn1Neg.deleteOnExit();
        tempFileFreqs.deleteOnExit();
        tempFileCodes.deleteOnExit();
        tempFileHuffman.deleteOnExit();

        try {
            writeWordVectors(vectors.lookupTable(), tempFileSyn0);

            FileUtils.copyFile(tempFileSyn0, zipfile);

            // writing out syn1
            INDArray syn1 = ((InMemoryLookupTable<VocabWord>) vectors.getLookupTable()).getSyn1();

            if (syn1 != null)
                try (PrintWriter writer = new PrintWriter(new FileWriter(tempFileSyn1))) {
                    for (int x = 0; x < syn1.rows(); x++) {
                        INDArray row = syn1.getRow(x);
                        StringBuilder builder = new StringBuilder();
                        for (int i = 0; i < row.length(); i++) {
                            builder.append(row.getDouble(i)).append(" ");
                        }
                        writer.println(builder.toString().trim());
                    }
                }

            ZipEntry zSyn1 = new ZipEntry("syn1.txt");
            zipfile.putNextEntry(zSyn1);

            FileUtils.copyFile(tempFileSyn1, zipfile);

            // writing out syn1
            INDArray syn1Neg = ((InMemoryLookupTable<VocabWord>) vectors.getLookupTable()).getSyn1Neg();

            if (syn1Neg != null)
                try (PrintWriter writer = new PrintWriter(new FileWriter(tempFileSyn1Neg))) {
                    for (int x = 0; x < syn1Neg.rows(); x++) {
                        INDArray row = syn1Neg.getRow(x);
                        StringBuilder builder = new StringBuilder();
                        for (int i = 0; i < row.length(); i++) {
                            builder.append(row.getDouble(i)).append(" ");
                        }
                        writer.println(builder.toString().trim());
                    }
                }

            ZipEntry zSyn1Neg = new ZipEntry("syn1Neg.txt");
            zipfile.putNextEntry(zSyn1Neg);

            FileUtils.copyFile(tempFileSyn1Neg, zipfile);


            ZipEntry hC = new ZipEntry("codes.txt");
            zipfile.putNextEntry(hC);

            // writing out huffman tree
            try (PrintWriter writer = new PrintWriter(new FileWriter(tempFileCodes))) {
                for (int i = 0; i < vectors.getVocab().numWords(); i++) {
                    VocabWord word = vectors.getVocab().elementAtIndex(i);
                    StringBuilder builder = new StringBuilder(encodeB64(word.getLabel())).append(" ");
                    for (int code : word.getCodes()) {
                        builder.append(code).append(" ");
                    }

                    writer.println(builder.toString().trim());
                }
            }

            FileUtils.copyFile(tempFileCodes, zipfile);

            ZipEntry hP = new ZipEntry("huffman.txt");
            zipfile.putNextEntry(hP);

            // writing out huffman tree
            try (PrintWriter writer = new PrintWriter(new FileWriter(tempFileHuffman))) {
                for (int i = 0; i < vectors.getVocab().numWords(); i++) {
                    VocabWord word = vectors.getVocab().elementAtIndex(i);
                    StringBuilder builder = new StringBuilder(encodeB64(word.getLabel())).append(" ");
                    for (int point : word.getPoints()) {
                        builder.append(point).append(" ");
                    }

                    writer.println(builder.toString().trim());
                }
            }

            FileUtils.copyFile(tempFileHuffman, zipfile);

            ZipEntry hF = new ZipEntry("frequencies.txt");
            zipfile.putNextEntry(hF);

            // writing out word frequencies
            try (PrintWriter writer = new PrintWriter(new FileWriter(tempFileFreqs))) {
                for (int i = 0; i < vectors.getVocab().numWords(); i++) {
                    VocabWord word = vectors.getVocab().elementAtIndex(i);
                    StringBuilder builder = new StringBuilder(encodeB64(word.getLabel())).append(" ")
                            .append(word.getElementFrequency()).append(" ")
                            .append(vectors.getVocab().docAppearedIn(word.getLabel()));

                    writer.println(builder.toString().trim());
                }
            }

            FileUtils.copyFile(tempFileFreqs, zipfile);

            ZipEntry config = new ZipEntry("config.json");
            zipfile.putNextEntry(config);
            //log.info("Current config: {}", vectors.getConfiguration().toJson());
            try (ByteArrayInputStream bais = new ByteArrayInputStream(vectors.getConfiguration().toJson().getBytes(StandardCharsets.UTF_8))) {
                IOUtils.copy(bais, zipfile);
            }

            zipfile.flush();
            zipfile.close();
        } finally {
            for (File f : new File[]{tempFileSyn0, tempFileSyn1, tempFileSyn1Neg, tempFileCodes, tempFileHuffman, tempFileFreqs}) {
                try {
                    f.delete();
                } catch (Exception e) {
                    //Ignore, is temp file
                }
            }
        }
    }
471728
def write_brainvision(data, filename, markers=None):
    
    filename = Path(filename).resolve().with_suffix('.vhdr')
    if markers is None:
        markers = []

    with filename.open('w') as f:
        f.write(_write_vhdr(data, filename))

    with filename.with_suffix('.vmrk').open('w') as f:
        f.write(_write_vmrk(data, filename, markers))

    _write_eeg(data, filename)
1197604
def write_file(file, b):
	
	if hasattr(file, "write_bytes"):
		file.write_bytes(b)
	elif hasattr(file, "write"):
		file.write(b)
	else:
		with open(file, "wb") as f:
			f.write(b)
1344366
def write_float_matrices(scp_path, ark_path, matrices):
        

        scp_entries = []

        with open(ark_path, 'wb') as f:
            for utterance_id in sorted(list(matrices.keys())):
                matrix = matrices[utterance_id]

                assert (matrix.dtype == np.float32)

                f.write(('{} '.format(utterance_id)).encode('utf-8'))

                offset = f.tell()

                f.write(b'\x00B')
                f.write(b'FM ')
                f.write(b'\x04')
                f.write(struct.pack('<i', np.size(matrix, 0)))
                f.write(b'\x04')
                f.write(struct.pack('<i', np.size(matrix, 1)))

                flattened = matrix.reshape(np.size(matrix, 0) * np.size(matrix, 1))
                flattened.tofile(f, sep='')

                scp_entries.append('{} {}:{}'.format(utterance_id, ark_path, offset))

        with open(scp_path, 'w') as f:
            f.write('\n'.join(scp_entries))
156393
def _write_cvvr(self, f, data):
        '''
        
        '''
        f.seek(0, 2)
        byte_loc = f.tell()
        cSize = len(data)
        block_size = CDF.CVVR_BASE_SIZE64 + cSize
        section_type = CDF.CVVR_
        rfuA = 0

        cvvr1 = bytearray(24)
        cvvr1[0:8] = struct.pack('>q', block_size)
        cvvr1[8:12] = struct.pack('>i', section_type)
        cvvr1[12:16] = struct.pack('>i', rfuA)
        cvvr1[16:24] = struct.pack('>q', cSize)
        f.write(cvvr1)
        f.write(data)

        return byte_loc
1210706
def write(self, filename):
        """"""
        if file_exists(filename):
            return filename
        out_files = [filename, filename + ".rownames", filename + ".colnames"]
        with file_transaction(out_files) as tx_out_files:
            with open(tx_out_files[0], "wb") as out_handle:
                scipy.io.mmwrite(out_handle, scipy.sparse.csr_matrix(self.matrix))
            pd.Series(self.rownames).to_csv(tx_out_files[1], index=False)
            pd.Series(self.colnames).to_csv(tx_out_files[2], index=False)
        return filename
248770
def write_file(self, blob, dest):
        '''
        
        '''
        with salt.utils.files.fopen(dest, 'wb+') as fp_:
            blob.stream_data(fp_)
203425
def write_desc(self) -> None:
        

        path = os.path.join(self.exp_dir, "model_description.txt")
        with open(path, "w") as desc_f:
            for key, val in self.__dict__.items():
                print("%s=%s" % (key, val), file=desc_f)

        import json
        json_path = os.path.join(self.exp_dir, "model_description.json")
        desc = { } #type: Dict[str, Any]
        # For use in decoding from a saved model
        desc["topology"] = {
            "batch_x_name" : self.batch_x.name, #type: ignore
            "batch_x_lens_name" : self.batch_x_lens.name, #type: ignore
            "dense_decoded_name" : self.dense_decoded.name #type: ignore
        }
        desc["model_type"] = str(self.__class__)
        for key, val in self.__dict__.items():
            if isinstance(val, int):
                desc[str(key)] = val
            elif isinstance(val, tf.Tensor):
                desc[key] = {
                    "type": "tf.Tensor",
                    "name": val.name, #type: ignore
                    "shape": str(val.shape), #type: ignore
                    "dtype" : str(val.dtype), #type: ignore
                    "value" : str(val),
                }
            elif isinstance(val, tf.SparseTensor): #type: ignore
                desc[key] = {
                    "type": "tf.SparseTensor",
                    "value": str(val), #type: ignore
                }
            else:
                desc[str(key)] = str(val)
        with open(json_path, "w") as json_desc_f:
            json.dump(desc, json_desc_f, skipkeys=True)
482281
def write_dfile(self):
        
        f_in = self.tempfiles.get_tempfile(prefix="bmds-", suffix=".(d)")
        with open(f_in, "w") as f:
            f.write(self.as_dfile())
        return f_in
152168
def join(input_files, output_file):
    '''
    
    '''

    # get feature collections
    final_features = []
    for file in input_files:
        with open(file) as f:
            feat_collection = geojson.load(f)
            final_features += feat_collection['features']

    feat_collection['features'] = final_features

    # write to output file
    with open(output_file, 'w') as f:
        geojson.dump(feat_collection, f)
597414
def write_cyc(fn, this, conv=1.0):
    

    lattice = this.get_cell()

    f = paropen(fn, "w")
    f.write("<------- Simulation box definition\n")
    f.write("<------- Barostat (on = 1, off = 0)\n")
    f.write("  0\n")
    f.write("<------- Box vectors (start)\n")
    f.write("  %20.10f %20.10f %20.10f\n" % (lattice[0][0]*conv, lattice[1][0]*conv, lattice[2][0]*conv))
    f.write("  %20.10f %20.10f %20.10f\n" % (lattice[0][1]*conv, lattice[1][1]*conv, lattice[2][1]*conv))
    f.write("  %20.10f %20.10f %20.10f\n" % (lattice[0][2]*conv, lattice[1][2]*conv, lattice[2][2]*conv))
    f.write("<------- Box vectors (end)\n")
    f.write("  %20.10f %20.10f %20.10f\n" % (lattice[0][0]*conv, lattice[1][0]*conv, lattice[2][0]*conv))
    f.write("  %20.10f %20.10f %20.10f\n" % (lattice[0][1]*conv, lattice[1][1]*conv, lattice[2][1]*conv))
    f.write("  %20.10f %20.10f %20.10f\n" % (lattice[0][2]*conv, lattice[1][2]*conv, lattice[2][2]*conv))
    f.write("<------- Mass and gamma of the box (used in connection with the barostat)\n")
    f.write("  240 0.005\n")
    f.write("<------- Stress tensor (start)\n")
    f.write("  0 0 0\n")
    f.write("  0 0 0\n")
    f.write("  0 0 0\n")
    f.write("<------- Stress tensor (end)\n")
    f.write("  0 0 0\n")
    f.write("  0 0 0\n")
    f.write("  0 0 0\n")
    f.close()