Example #1
0
double gradSolver(double *A, double *b, double *x, int n, double e,
        int it, double *timeGrad, double *timeError){
    int i = 0;
    double prev_norm, norm;
    double *r = (double *) malloc(n*sizeof(double));


    memset(x, 0, n*sizeof(double));
    *timeGrad = *timeError = 0.0;

    *timeError -= timestamp();
    residue(A, b, x, r, n);
    *timeError += timestamp();
    prev_norm = residualNorm(r, n);

    double absErr = e + 1.0;
    while ((fabs(absErr) > e) && (i++<it)){
        *timeGrad -= timestamp();
        calcGrad(A, x, r, n);
        *timeGrad += timestamp();
        *timeError -= timestamp();
        residue(A, b, x, r, n);
        *timeError += timestamp();
        norm = residualNorm(r, n);
        absErr = norm - prev_norm;
        prev_norm = norm;
    }

    //*timeGrad /= i;

    free(r);
    return norm;
}
Example #2
0
long int Molecule::addResidue(std::string name, int resnum)
{
    Residue residue(name, resnum);
    long int result = residues.size();
    residues.push_back(residue);
    return result;
}
bool bounded_max_flow(graph_matrix upper, graph_matrix lower,
		int beg, int end, int& max_flow)
{//流网络有g_cnt个节点,下标从0到g_cnt-1,upper为上界容量,lower为下界容量
 //返回有源汇容量有上下界的流网络中是否存在可行流,若存在返回最大流max_flow
	max_flow = 0;
	//n_upper和n_lower是有源汇网络对应的无源汇网络
	graph_matrix n_upper(upper), n_lower(lower);
	//构造无源汇网络n_upper和n_lower,添加一条从end到beg的无穷大的边
	construct_n(n_upper, beg, end);
	//s_beg为超级源点,s_end为超级汇点
	int s_beg, s_end;
	graph_matrix residue(n_upper);
	residue.g_cnt += 2;
	s_beg = residue.g_cnt - 2;
	s_end = residue.g_cnt - 1;
	//将residue构造为无源汇网络对应的普通流网络
	construct_c(n_upper, n_lower, s_beg, s_end, residue);
	int lower_max_flow = distance_label(residue, s_beg, s_end);
	int s_beg_out = beg_out(residue, s_beg, n_upper.g_cnt);
	//若不相等则不存在可行流,也不存在最大流
	if(lower_max_flow != s_beg_out)
		return(false);

	//若存在可行流,则计算最大流
	//将residue中的超级源点超级汇点和原汇点到源点的边删去
	deconstruct_c(residue, s_beg, s_end, beg, end);
	int free_max_flow = distance_label(residue, beg, end);
	max_flow = lower_max_flow + free_max_flow;
	return(true);
}
bool bounded_min_flow(graph_matrix upper, graph_matrix lower,
		int beg, int end, int& min_flow)
{//流网络有g_cnt个节点,下标从0到g_cnt-1,upper为上界容量,lower为下界容量
 //返回有源汇容量有上下界的流网络中是否存在可行流,若存在返回最小流min_flow
	min_flow = 0;
	graph_matrix n_upper(upper), n_lower(lower);
	int s_beg, s_end;
	graph_matrix residue(n_upper);
	residue.g_cnt += 2;
	s_beg = residue.g_cnt - 2;
	s_end = residue.g_cnt - 1;
	construct_c(n_upper, n_lower, s_beg, s_end, residue);
	//第一次计算最大流
	int lower_max_flow = distance_label(residue, s_beg, s_end);
	int s_beg_out = beg_out(residue, s_beg, n_upper.g_cnt);
	//若第一次最大流已经等于超级源点所有出弧边容量之和,即已经满负荷
	if(lower_max_flow == s_beg_out)
		return(false);

	//若lower_max_flow < s_beg_out,即尚未满负荷
	//添加从汇点end到源点beg容量无穷大的边
	construct_n(residue, beg, end);
	//再次计算最大流
	//由于计算从汇点end到源点beg边上的流需要更改distance_label代码,不方便扩展
	//所以本文略去具体的代码(读者只需要对distance_label代码稍作更改即可求出min_flow)
	int lower_max_flow2 = distance_label(residue, s_beg, s_end);
	int s_beg_out2 = beg_out(residue, s_beg, n_upper.g_cnt);
	if(lower_max_flow2 == s_beg_out2)
		return(true);
	else
		return(false);
}
Example #5
0
MultiChannelResult Mmp2Decomposition::compute(const DecompositionSettings& settings, const WorkspaceBuilder& builder, const MultiSignal& signal) {
	MultiSignal sum;
	const int N = signal.getSampleCount();
	const int channelCount = signal.channels.size();
	sum.channels.push_back(signal.channels[0]);
	for (int c=1; c<channelCount; ++c) {
		for (int i=0; i<N; ++i) {
			sum.channels[0].samples[i] += signal.channels[c].samples[i];
		}
	}

	Atoms sumResult = Decomposition::compute(settings, builder, sum)[0];

	MultiSignal residue(signal);
	MultiChannelResult result(channelCount);
	for (int c=0; c<channelCount; ++c) {
		for (Atom atom : sumResult) {
			Workspace::subtractAtomFromSignal(atom, residue.channels[c], true);
			result[c].push_back(atom);
		}
	}
	return result;
}
Example #6
0
void PDBFormat::PDBParser::parseSequence(BioStruct3D& biostruct, U2OpStatus& ti)
{
    Q_UNUSED(biostruct);
    /*
    Record Format

    COLUMNS     DEFINITION
    1 - 6       Record name "SEQRES"
    8 - 10      Integer serNum Serial number of the SEQRES record for the current chain.
                Starts at 1 and increments by one each line. Reset to 1 for each chain.
    12          Character chainID Chain identifier. This may be any single legal character,
                including a blank which is is used if there is only one chain.
    14 - 17     Integer numRes Number of residues in the chain.
                This value is repeated on every record.
    20 - ...    Residues
    */


    if (currentPDBLine.length() < 24 /* at least one residue */)
    {
        ti.setError(U2::PDBFormat::tr("Invalid SEQRES: less then 24 characters"));
        return;
    }

    char chainIdentifier = currentPDBLine.at(11).toLatin1();
    if (!seqResMap.contains(chainIdentifier)) {
        seqResMap.insert(chainIdentifier, QByteArray());
    }

    QStringList residues = currentPDBLine.mid(19).split(QRegExp("\\s+"), QString::SkipEmptyParts);
    QByteArray sequencePart;
    foreach (QString name, residues) {
        SharedResidue residue(new ResidueData);
        char acronym = PDBFormat::getAcronymByName(name.toLatin1());
        sequencePart.append(acronym);
    }
Example #7
0
Dispersive::Dispersive(const Id id,
                                   const std::string& name,
                                   const Math::Real rEps,
                                   const Math::Real rMu,
                                   const Math::Real elecCond,
                                   const Math::Real magnCond,
                                   const std::vector<PoleResidue>& poleResidue)
:   Identifiable<Id>(id),
    PhysicalModel(name) {
    rEpsInfty_ = rEps;
    rMuInfty_ = rMu;
    // Adds conductivity as a permittivity pole.
    if (elecCond != 0.0) {
        std::complex<Math::Real> pole(0.0);
        std::complex<Math::Real> residue(elecCond / Math::Real(2.0) /
                                         Math::Constants::eps0, 0);
        poleResidue_.push_back(PoleResidue(pole, residue));
    }
    //
    if (magnCond != 0.0) {
        throw std::logic_error("Dispersive magnetic materials not implemented");
    }
    poleResidue_ = poleResidue;
}
Example #8
0
/*----------------------------------------------------------------------------
 * Post - adaptive postfilter main function
 *----------------------------------------------------------------------------
 */
void poste(
    int   t0,             /* input : pitch delay given by coder */
    FLOAT *signal_ptr,    /* input : input signal (pointer to current subframe */
    FLOAT *coeff,         /* input : LPC coefficients for current subframe */
    FLOAT *sig_out,       /* output: postfiltered output */
    int   *vo,            /* output: voicing decision 0 = uv,  > 0 delay */
    FLOAT gamma1,         /* input: short term postfilt. den. weighting factor*/
    FLOAT gamma2,         /* input: short term postfilt. num. weighting factor*/
    FLOAT gamma_harm,     /* input: long term postfilter weighting factor*/
    int   long_h_st,      /* input: impulse response length*/
    int   m_pst,          /* input:  LPC order */
    int Vad               /* input : VAD information (frame type)  */
)
{

    /* Local variables and arrays */
    FLOAT apond1[M_BWDP1];             /* s.t. denominator coeff.      */
    FLOAT sig_ltp[L_SUBFRP1];      /* H0 output signal             */
    FLOAT *sig_ltp_ptr;
    FLOAT parcor0;

    /* Compute weighted LPC coefficients */
    weight_az(coeff, gamma1, m_pst, apond1);
    weight_az(coeff, gamma2, m_pst, apond2);
    set_zero(&apond2[m_pst+1], (M_BWD-m_pst));

    /* Compute A(gamma2) residual */
    residue(m_pst, apond2, signal_ptr, res2_ptr, L_SUBFR);

    /* Harmonic filtering */
    sig_ltp_ptr = sig_ltp + 1;

    if (Vad > 1)
      pst_ltpe(t0, res2_ptr, sig_ltp_ptr, vo, gamma_harm);
    else {
      *vo = 0;
      copy(res2_ptr, sig_ltp_ptr, L_SUBFR);
    }

    /* Save last output of 1/A(gamma1)  */
    /* (from preceding subframe)        */
    sig_ltp[0] = *ptr_mem_stp;

    /* Controls short term pst filter gain and compute parcor0   */
    calc_st_filte(apond2, apond1, &parcor0, sig_ltp_ptr, long_h_st, m_pst);

    /* 1/A(gamma1) filtering, mem_stp is updated */
    syn_filte(m_pst, apond1, sig_ltp_ptr, sig_ltp_ptr, L_SUBFR,
            &mem_stp[M_BWD-m_pst], 0);
    copy(&sig_ltp_ptr[L_SUBFR-M_BWD], mem_stp, M_BWD);

    /* Tilt filtering */
    filt_mu(sig_ltp, sig_out, parcor0);

    /* Gain control */
    scale_st(signal_ptr, sig_out, &gain_prec);

    /**** Update for next subframe */
    copy(&res2[L_SUBFR], &res2[0], MEM_RES2);

    return;
}
Example #9
0
void set_lpc_mode(float * signal_ptr,	/* I   Input signal */
		  float * a_fwd,	/* I   Forward LPC filter */
		  float * a_bwd,	/* I   Backward LPC filter */
		  int *mode,	/* O  Backward / forward Indication */
		  float * lsp_new,	/* I   LSP vector current frame */
		  float * lsp_old,	/* I   LSP vector previous frame */
		  int *bwd_dominant,	/* O   Bwd dominant mode indication */
		  int prev_mode,	/* I   previous frame Backward / forward Indication */
		  float * prev_filter,	/* I   previous frame filter */
		  float * C_int,	/*I/O filter interpolation parameter */
		  int16_t * glob_stat,	/* I/O Mre of global stationnarity */
		  int16_t * stat_bwd,	/* I/O Number of consecutive backward frames */
		  int16_t * val_stat_bwd	/* I/O Value associated with stat_bwd */
    )
{

	int i;
	float res[L_FRAME];
	float *pa_bwd;
	float gap;
	float gpred_f, gpred_b, gpred_bint;
	float tmp;
	float thresh_lpc;
	float dist_lsp, energy;

	pa_bwd = a_bwd + M_BWDP1;
	/* Backward filter prediction gain (no interpolation ) */
	/* --------------------------------------------------- */
	residue(M_BWD, pa_bwd, signal_ptr, res, L_FRAME);
	gpred_b = ener_dB(signal_ptr, L_FRAME) - ener_dB(res, L_FRAME);

	/* Interpolated LPC filter for transition forward -> backward */
	/* (used during 10 frames) ( for the second sub-frame )       */
	/* Interpolated backward filter for the first sub-frame       */
	/* ---------------------------------------------------------- */
	int_bwd(a_bwd, prev_filter, C_int);

	/* Interpolated backward filter prediction gain */
	/* -------------------------------------------- */
	residue(M_BWD, a_bwd, signal_ptr, res, L_SUBFR);
	residue(M_BWD, pa_bwd, &signal_ptr[L_SUBFR], &res[L_SUBFR], L_SUBFR);
	gpred_bint = ener_dB(signal_ptr, L_FRAME) - ener_dB(res, L_FRAME);

	/* Forward filter prediction gain */
	/* ------------------------------ */
	residue(M, a_fwd, signal_ptr, res, L_SUBFR);
	residue(M, &a_fwd[MP1], &signal_ptr[L_SUBFR], &res[L_SUBFR], L_SUBFR);
	gpred_f = ener_dB(signal_ptr, L_FRAME) - ener_dB(res, L_FRAME);

	/* -------------------------------------------------------------- */
	/*                  BACKWARD / FORWARD DECISION                   */
	/*                                                                */
	/* The Main criterion is based on the prediction gains :          */
	/* The global stationnarity index is used to adapt the threshold  */
	/* value " GAP ".                                                 */
	/* This adaptation is used to favour one mode according to the    */
	/* stationnarity of the input signal (backward for music and      */
	/* forward for speech) which avoids too many switches.            */
	/*                                                                */
	/* A second criterion based on the LSPs is used to avoid switches */
	/* if the successive LPC forward filters are very stationnary     */
	/* (which is measured a Euclidean distance on LSPs).              */
	/*                                                                */
	/* -------------------------------------------------------------- */

	/* 1st criterion with prediction gains */
	/* ----------------------------------- */

	/* Threshold adaptation according to the global stationnarity indicator */
	gap = (float) (*glob_stat) * GAP_FACT;
	gap += (float) 1.;

	if ((gpred_bint > gpred_f - gap) && (gpred_b > gpred_f - gap) &&
	    (gpred_b > (float) 0.) && (gpred_bint > (float) 0.))
		*mode = 1;
	else
		*mode = 0;

	if (*glob_stat < 13000)
		*mode = 0;	/* => Forward mode imposed */

	/* 2nd criterion with a distance between 2 successive LSP vectors */
	/* -------------------------------------------------------------- */
	/* Computation of the LPC distance */
	dist_lsp = 0;
	for (i = 0; i < M; i++) {
		tmp = lsp_old[i] - lsp_new[i];
		dist_lsp += tmp * tmp;
	}

	/* Adaptation of the LSPs thresholds */
	if (*glob_stat < 32000) {
		thresh_lpc = (float) 0.;
	} else {
		thresh_lpc = (float) 0.03;
	}

	/* Switching backward -> forward forbidden in case of a LPC stationnary */
	if ((dist_lsp < thresh_lpc) && (*mode == 0) && (prev_mode == 1)
	    && (gpred_b > (float) 0.) && (gpred_bint > (float) 0.)) {
		*mode = 1;
	}

	/* Low energy frame => Forward mode chosen */
	/* --------------------------------------- */
	energy = ener_dB(signal_ptr, L_FRAME);

	if (energy < THRES_ENERGY) {
		*mode = 0;
		if (*glob_stat > 13000)
			*glob_stat = 13000;
	} else
		tst_bwd_dominant(bwd_dominant, *mode);

	/* Adaptation of the global stationnarity indicator */
	/* ------------------------------------------------ */
	if (energy >= THRES_ENERGY)
		calc_stat(gpred_b, gpred_f, *mode,
			  prev_mode, glob_stat, stat_bwd, val_stat_bwd);
	if (*mode == 0)
		*C_int = (float) 1.1;
	return;
}
Example #10
0
void PDBFormat::PDBParser::parseAtom(BioStruct3D& biostruct, U2OpStatus&)
{
    /*
    Record Format

    COLUMNS     DEFINITION
    1 - 6       Record name "ATOM "
    7 - 11      Atom serial number.
    13 - 16     Atom name.
    17          Alternate location indicator.
    18 - 20     Residue name.
    22          Chain identifier.
    23 - 26     Residue sequence number.
    27          Code for insertion of residues.
    31 - 38     Orthogonal coordinates for X in Angstroms.
    39 - 46     Orthogonal coordinates for Y in Angstroms.
    47 - 54     Orthogonal coordinates for Z in Angstroms.
    55 - 60     Occupancy.
    61 - 66     Temperature factor.
    77 - 78     Element symbol, right-justified.
    79 - 80     Charge on the atom.
    */

    if (!flagAtomRecordPresent)
        flagAtomRecordPresent = true;

    bool isHetero = false;
    if (currentPDBLine.startsWith("HETATM")) {
        isHetero = true;
    }

    int id = currentPDBLine.mid(6,5).toInt();
    QByteArray atomName = currentPDBLine.mid(12,4).toLatin1().trimmed();
    QByteArray residueName = currentPDBLine.mid(17,3).toLatin1().trimmed();
    int resId = currentPDBLine.mid(22,4).toLatin1().toInt();
    char insCode = currentPDBLine.at(26).toLatin1();
    char residueAcronym = PDBFormat::getAcronymByName(residueName);
    char chainIdentifier = currentPDBLine.at(21).toLatin1();

    ResidueIndex residueIndex(resId,insCode);
    bool atomIsInChain = !isHetero || seqResContains(chainIdentifier, residueIndex.toInt(), residueAcronym);

    QByteArray elementName = currentPDBLine.mid(76,2).toLatin1().trimmed();

    QByteArray element = elementName.isEmpty() ? atomName.mid(0,1) : elementName;
    int atomicNumber = PDBFormat::getElementNumberByName(element);

    int chainIndex = chainIndexMap.contains(chainIdentifier) ? chainIndexMap.value(chainIdentifier) : currentChainIndex;

    if (currentModelIndex == 0 && atomIsInChain) {

        // Process residue

        if (!biostruct.moleculeMap.contains(chainIndex)) {
            createMolecule(chainIdentifier, biostruct, chainIndex);
        }

        SharedMolecule& mol = biostruct.moleculeMap[chainIndex];

        if (currentResidueIndex != residueIndex)  {
            SharedResidue residue(new ResidueData);
            residue->name = residueName;
            residue->acronym = residueAcronym;
            if (residue->acronym == 'X') {
                ioLog.details(tr("PDB warning: unknown residue name: %1").arg(residue->name.constData()));
            }
            residue->chainIndex = chainIndex;
            currentResidueIndex = residueIndex;
            residueOrder++;
            residueIndex.setOrder(residueOrder);
            mol->residueMap.insert(residueIndex, residue);
        }

    }

    // Process atom
    double x,y,z;
    x = currentPDBLine.mid(30,8).toDouble();
    y = currentPDBLine.mid(38,8).toDouble();
    z = currentPDBLine.mid(46,8).toDouble();
    double occupancy = currentPDBLine.mid(54,6).toDouble();
    double temperature = currentPDBLine.mid(60,6).toDouble();

    SharedAtom a(new AtomData);
    a->chainIndex = chainIndex;
    a->residueIndex = residueIndex;
    a->atomicNumber = atomicNumber;
    a->name = atomName;
    a->coord3d = Vector3D(x,y,z);
    a->occupancy = occupancy;
    a->temperature = temperature;

    biostruct.modelMap[currentModelIndex + 1].insert(id, a);

    if (atomIsInChain) {
        SharedMolecule& mol = biostruct.moleculeMap[chainIndex];
        Molecule3DModel& model3D = mol->models[currentModelIndex];
        model3D.atoms.insert(id, a);
    }

}
			residue get_residue_with_insert_without_ss() {
				return residue( make_residue_id( 'A', 43, 'A' ), vaa, coord::ORIGIN_COORD, coord::ORIGIN_COORD, 3, sec_struc_type::ALPHA_HELIX, rotation::IDENTITY_ROTATION(), residue::DEFAULT_PHI_PSI(), residue::DEFAULT_PHI_PSI(), 0 );
			}