Save eigenvalue analysis reports

        Returns
        -------
        None
184422
def dump_results(self):
        
        system = self.system
        mu = self.mu
        partfact = self.part_fact

        if system.files.no_output:
            return

        text = []
        header = []
        rowname = []
        data = []

        neig = len(mu)
        mu_real = mu.real()
        mu_imag = mu.imag()
        npositive = sum(1 for x in mu_real if x > 0)
        nzero = sum(1 for x in mu_real if x == 0)
        nnegative = sum(1 for x in mu_real if x < 0)

        numeral = []
        for idx, item in enumerate(range(neig)):
            if mu_real[idx] == 0:
                marker = '*'
            elif mu_real[idx] > 0:
                marker = '**'
            else:
                marker = ''
            numeral.append('#' + str(idx + 1) + marker)

        # compute frequency, undamped frequency and damping
        freq = [0] * neig
        ufreq = [0] * neig
        damping = [0] * neig
        for idx, item in enumerate(mu):
            if item.imag == 0:
                freq[idx] = 0
                ufreq[idx] = 0
                damping[idx] = 0
            else:
                freq[idx] = abs(item) / 2 / pi
                ufreq[idx] = abs(item.imag / 2 / pi)
                damping[idx] = -div(item.real, abs(item)) * 100

        # obtain most associated variables
        var_assoc = []
        for prow in range(neig):
            temp_row = partfact[prow, :]
            name_idx = list(temp_row).index(max(temp_row))
            var_assoc.append(system.varname.unamex[name_idx])

        pf = []
        for prow in range(neig):
            temp_row = []
            for pcol in range(neig):
                temp_row.append(round(partfact[prow, pcol], 5))
            pf.append(temp_row)

        text.append(system.report.info)
        header.append([''])
        rowname.append(['EIGENVALUE ANALYSIS REPORT'])
        data.append('')

        text.append('STATISTICS\n')
        header.append([''])
        rowname.append(['Positives', 'Zeros', 'Negatives'])
        data.append([npositive, nzero, nnegative])

        text.append('EIGENVALUE DATA\n')
        header.append([
            'Most Associated', 'Real', 'Imag', 'Damped Freq.', 'Frequency',
            'Damping [%]'
        ])
        rowname.append(numeral)
        data.append(
            [var_assoc,
             list(mu_real),
             list(mu_imag), ufreq, freq, damping])

        cpb = 7  # columns per block
        nblock = int(ceil(neig / cpb))

        if nblock <= 100:
            for idx in range(nblock):
                start = cpb * idx
                end = cpb * (idx + 1)
                text.append('PARTICIPATION FACTORS [{}/{}]\n'.format(
                    idx + 1, nblock))
                header.append(numeral[start:end])
                rowname.append(system.varname.unamex)
                data.append(pf[start:end])

        dump_data(text, header, rowname, data, system.files.eig)
        logger.info('report saved.')
609435
def GET_save_timegrid(self) -> None:
        """"""
        state.timegrids[self._id] = copy.deepcopy(hydpy.pub.timegrids.sim)
403201
def dump(archive, calc_id=0, user=None):
    
    t0 = time.time()
    assert archive.endswith('.zip'), archive
    getfnames = 'select ds_calc_dir || ".hdf5" from job where ?A'
    param = dict(status='complete')
    if calc_id:
        param['id'] = calc_id
    if user:
        param['user_name'] = user
    fnames = [f for f, in db(getfnames, param) if os.path.exists(f)]
    zipfiles(fnames, archive, 'w', safeprint)
    pending_jobs = db('select id, status, description from job '
                      'where status="executing"')
    if pending_jobs:
        safeprint('WARNING: there were calculations executing during the dump,'
                  ' they have been not copied')
        for job_id, status, descr in pending_jobs:
            safeprint('%d %s %s' % (job_id, status, descr))

    # this also checks that the copied db is not corrupted
    smart_save(db.path, archive, calc_id)

    dt = time.time() - t0
    safeprint('Archived %d calculations into %s in %d seconds'
              % (len(fnames), archive, dt))
1054087
def do_save(self, fp=None):
        
        if fp is None:
            fp = sys.stdout
        data = {
            'settings': self.settings,
            'nodes': self.nodes,
            'backward': self.backward
        }
        json.dump(data, fp, ensure_ascii=False)
1121227
def run(self, verbose=True):
        
        self.results.clear()

        for analysis_group in self.config.analysis_groups:
            if analysis_group.providers:
                for provider in analysis_group.providers:
                    logger.info('Run provider %s', provider.identifier)
                    provider.run()
                    for checker in analysis_group.checkers:
                        result = self._get_checker_result(
                            analysis_group, checker, provider)
                        self.results.append(result)
                        analysis_group.results.append(result)
                        if verbose:
                            result.print()
            else:
                for checker in analysis_group.checkers:
                    result = self._get_checker_result(
                        analysis_group, checker, nd='no-data-')
                    self.results.append(result)
                    analysis_group.results.append(result)
                    if verbose:
                        result.print()
1361461
def eighCovarianceMatrix(cfile):
    
    # precompute eigenvalue decomposition
    K = np.loadtxt(cfile+'.cov')
    K+= 1e-4*sp.eye(K.shape[0])
    S,U = la.eigh(K); S=S[::-1]; U=U[:,::-1]
    np.savetxt(cfile+'.cov.eval',S,fmt='%.6f')
    np.savetxt(cfile+'.cov.evec',U,fmt='%.6f')
1024007
def save_batch(server_context, assay_id, batch):
    # type: (ServerContext, int, Batch) -> Union[Batch, None]
    
    result = save_batches(server_context, assay_id, [batch])

    if result is not None:
        return result[0]
    return None
280820
def save_report(session):
    '''
    
    '''
    # prune this folder to contain the last 10 sessions
    previous_reports = glob.glob(os.path.join(report_dir(), '*.pyireport'))
    previous_reports.sort(reverse=True)
    while len(previous_reports) > 10:
        report_file = previous_reports.pop()
        os.remove(report_file)

    identifier = time.strftime('%Y-%m-%dT%H-%M-%S', time.localtime(session.start_time))

    path = os.path.join(
        report_dir(),
        identifier + '.pyireport'
    )
    session.save(path)
    return path, identifier
360514
def _ContinueReportCompilation(self):
    
    analyzer_alive = self._analyzer.is_alive()
    hash_queue_has_tasks = self.hash_queue.unfinished_tasks > 0
    analysis_queue = not self.hash_analysis_queue.empty()

    # pylint: disable=consider-using-ternary
    return (analyzer_alive and hash_queue_has_tasks) or analysis_queue
20921
def save_transform(self) -> str:
        
        expected = [self._expected_points[p][:2] for p in [1, 2, 3]]
        log.debug("save_transform expected: {}".format(expected))
        actual = [self.actual_points[p][:2] for p in [1, 2, 3]]
        log.debug("save_transform actual: {}".format(actual))
        # Generate a 2 dimensional transform matrix from the two matricies
        flat_matrix = solve(expected, actual)
        log.debug("save_transform flat_matrix: {}".format(flat_matrix))
        current_z = self.calibration_matrix[2][3]
        # Add the z component to form the 3 dimensional transform
        self.calibration_matrix = add_z(flat_matrix, current_z)

        gantry_calibration = list(
                map(lambda i: list(i), self.calibration_matrix))
        log.debug("save_transform calibration_matrix: {}".format(
            gantry_calibration))

        self.hardware.update_config(gantry_calibration=gantry_calibration)
        res = str(self.hardware.config)

        return '{}\n{}'.format(res, save_config(self.hardware.config))
1061379
def save_all
      reports = to_h
      reports.each do |file, report|
        File.write(file, report)
      end

      reports.keys
    end
279976
def calc_eigvals(self):
        
        self.eigs = numpy.linalg.eigvals(self.As)
        # TODO: use scipy.sparse.linalg.eigs(self.As)

        return self.eigs
627454
def save_disagg_to_csv(metadata, matrices):
    
    skip_keys = ('Mag', 'Dist', 'Lon', 'Lat', 'Eps', 'TRT')
    base_header = ','.join(
        '%s=%s' % (key, value) for key, value in metadata.items()
        if value is not None and key not in skip_keys)
    for disag_tup, (poe, iml, matrix, fname) in matrices.items():
        header = '%s,poe=%.7f,iml=%.7e\n' % (base_header, poe, iml)

        if disag_tup == ('Mag', 'Lon', 'Lat'):
            matrix = numpy.swapaxes(matrix, 0, 1)
            matrix = numpy.swapaxes(matrix, 1, 2)
            disag_tup = ('Lon', 'Lat', 'Mag')

        axis = [metadata[v] for v in disag_tup]
        header += ','.join(v for v in disag_tup)
        header += ',poe'

        # compute axis mid points
        axis = [(ax[: -1] + ax[1:]) / 2. if ax.dtype == float
                else ax for ax in axis]

        values = None
        if len(axis) == 1:
            values = numpy.array([axis[0], matrix.flatten()]).T
        else:
            grids = numpy.meshgrid(*axis, indexing='ij')
            values = [g.flatten() for g in grids]
            values.append(matrix.flatten())
            values = numpy.array(values).T

        writers.write_csv(fname, values, comment=header, fmt='%.5E')
53850
def results(self):
        """"""

        # Add all saved samples to the results.
        if self.save_samples:
            with warnings.catch_warnings():
                warnings.simplefilter("ignore")
                results = [('nlive', self.nlive),
                           ('niter', self.it - 1),
                           ('ncall', np.array(self.saved_nc)),
                           ('eff', self.eff),
                           ('samples', np.array(self.saved_v)),
                           ('samples_id', np.array(self.saved_id)),
                           ('samples_it', np.array(self.saved_it)),
                           ('samples_u', np.array(self.saved_u)),
                           ('logwt', np.array(self.saved_logwt)),
                           ('logl', np.array(self.saved_logl)),
                           ('logvol', np.array(self.saved_logvol)),
                           ('logz', np.array(self.saved_logz)),
                           ('logzerr', np.sqrt(np.array(self.saved_logzvar))),
                           ('information', np.array(self.saved_h))]
        else:
            raise ValueError("You didn't save any samples!")

        # Add any saved bounds (and ancillary quantities) to the results.
        if self.save_bounds:
            results.append(('bound', copy.deepcopy(self.bound)))
            results.append(('bound_iter',
                            np.array(self.saved_bounditer, dtype='int')))
            results.append(('samples_bound',
                            np.array(self.saved_boundidx, dtype='int')))
            results.append(('scale', np.array(self.saved_scale)))

        return Results(results)
4221
def write(self)->None:
        ""
        for param_name, values in self.params: self._write_histogram(param_name=param_name, values=values)
681380
def confindr_reporter(self, analysistype='confindr'):
        
        # Initialise the data strings
        data = 'Strain,Genus,NumContamSNVs,ContamStatus,PercentContam,PercentContamSTD\n'
        with open(os.path.join(self.reportpath, analysistype + '.csv'), 'w') as report:
            # Iterate through all the results
            for sample in self.runmetadata.samples:
                data += '{str},{genus},{numcontamsnv},{status},{pc},{pcs}\n'.format(
                    str=sample.name,
                    genus=sample.confindr.genus,
                    numcontamsnv=sample.confindr.num_contaminated_snvs,
                    status=sample.confindr.contam_status,
                    pc=sample.confindr.percent_contam,
                    pcs=sample.confindr.percent_contam_std
                )
            # Write the string to the report
            report.write(data)
140950
def write(self)->None:
        ""
        if len(self.gradients) == 0: return
        norms = [x.data.norm() for x in self.gradients]
        self._write_avg_norm(norms=norms)
        self._write_median_norm(norms=norms)
        self._write_max_norm(norms=norms)
        self._write_min_norm(norms=norms)
        self._write_num_zeros()
        self._write_avg_gradient()
        self._write_median_gradient()
        self._write_max_gradient()
        self._write_min_gradient()