Example #1
0
double FormantTier_getBandwidthAtTime (FormantTier me, int iformant, double t) {
	long n = my points.size;
	if (n == 0) return 0.0;
	FormantPoint pointRight = my points.at [1];
	if (t <= pointRight -> number) {
		if (iformant > pointRight -> numberOfFormants) return NUMundefined;
		return pointRight -> bandwidth [iformant-1];   // constant extrapolation
	}
	FormantPoint pointLeft = my points.at [n];
	if (t >= pointLeft -> number) {
		if (iformant > pointLeft -> numberOfFormants) return NUMundefined;
		return pointLeft -> bandwidth [iformant-1];   // constant extrapolation
	}
	Melder_assert (n >= 2);
	long ileft = AnyTier_timeToLowIndex (me->asAnyTier(), t), iright = ileft + 1;
	Melder_assert (ileft >= 1 && iright <= n);
	pointLeft = my points.at [ileft];
	pointRight = my points.at [iright];
	double tleft = pointLeft -> number;
	double fleft = iformant > pointLeft -> numberOfFormants ? NUMundefined : pointLeft -> bandwidth [iformant-1];
	double tright = pointRight -> number;
	double fright = iformant > pointRight -> numberOfFormants ? NUMundefined : pointRight -> bandwidth [iformant-1];
	return fleft == NUMundefined ? fright == NUMundefined ? NUMundefined : fright
		: fright == NUMundefined ? fleft
		: t == tright ? fright   // be very accurate
		: tleft == tright ? 0.5 * (fleft + fright)   // unusual, but possible; no preference
		: fleft + (t - tleft) * (fright - fleft) / (tright - tleft);   // linear interpolation
}
Example #2
0
void structSoundEditor :: v_createMenus () {
	SoundEditor_Parent :: v_createMenus ();
	Melder_assert (data != NULL);
	Melder_assert (d_sound.data != NULL || d_longSound.data != NULL);

	Editor_addCommand (this, L"Edit", L"-- cut copy paste --", 0, NULL);
	if (d_sound.data) cutButton = Editor_addCommand (this, L"Edit", L"Cut", 'X', menu_cb_Cut);
	copyButton = Editor_addCommand (this, L"Edit", L"Copy selection to Sound clipboard", 'C', menu_cb_Copy);
	if (d_sound.data) pasteButton = Editor_addCommand (this, L"Edit", L"Paste after selection", 'V', menu_cb_Paste);
	if (d_sound.data) {
		Editor_addCommand (this, L"Edit", L"-- zero --", 0, NULL);
		zeroButton = Editor_addCommand (this, L"Edit", L"Set selection to zero", 0, menu_cb_SetSelectionToZero);
		reverseButton = Editor_addCommand (this, L"Edit", L"Reverse selection", 'R', menu_cb_ReverseSelection);
	}

	if (d_sound.data) {
		Editor_addCommand (this, L"Select", L"-- move to zero --", 0, 0);
		Editor_addCommand (this, L"Select", L"Move start of selection to nearest zero crossing", ',', menu_cb_MoveBtoZero);
		Editor_addCommand (this, L"Select", L"Move begin of selection to nearest zero crossing", Editor_HIDDEN, menu_cb_MoveBtoZero);
		Editor_addCommand (this, L"Select", L"Move cursor to nearest zero crossing", '0', menu_cb_MoveCursorToZero);
		Editor_addCommand (this, L"Select", L"Move end of selection to nearest zero crossing", '.', menu_cb_MoveEtoZero);
	}

	v_createMenus_analysis ();
}
Example #3
0
PointProcess Sound_Pitch_to_PointProcess_peaks (Sound sound, Pitch pitch, int includeMaxima, int includeMinima) {
	PointProcess point = PointProcess_create (sound -> xmin, sound -> xmax, 10);
	double t = pitch -> xmin;
	double addedRight = -1e300;
	/*
	 * Cycle over all voiced intervals.
	 */

	for (;;) {
		double tleft, tright, tmiddle, f0middle, tmax, tsave;
		if (! Pitch_getVoicedIntervalAfter (pitch, t, & tleft, & tright)) break;
		/*
		 * Go to the middle of the voiced interval.
		 */
		tmiddle = (tleft + tright) / 2;
		if (! Melder_progress1 ((tmiddle - sound -> xmin) / (sound -> xmax - sound -> xmin), L"Sound & Pitch to PointProcess"))
			goto end;
		f0middle = Pitch_getValueAtTime (pitch, tmiddle, kPitch_unit_HERTZ, Pitch_LINEAR);

		/*
		 * Our first point is near this middle.
		 */
		Melder_assert (NUMdefined (f0middle));
		tmax = Sound_findExtremum (sound, tmiddle - 0.5 / f0middle, tmiddle + 0.5 / f0middle, includeMaxima, includeMinima);
		Melder_assert (NUMdefined (tmax));
		if (! PointProcess_addPoint (point, tmax)) goto end;

		tsave = tmax;
		for (;;) {
			double f0 = Pitch_getValueAtTime (pitch, tmax, kPitch_unit_HERTZ, Pitch_LINEAR);
			if (f0 == NUMundefined) break;
			tmax = Sound_findExtremum (sound, tmax - 1.25 / f0, tmax - 0.8 / f0, includeMaxima, includeMinima);
			if (tmax < tleft) {
				if (tmax - addedRight > 0.8 / f0)
					if (! PointProcess_addPoint (point, tmax)) goto end;
				break;
			}
			if (tmax - addedRight > 0.8 / f0)   /* Do not fill in a short originally unvoiced interval twice. */
				if (! PointProcess_addPoint (point, tmax)) goto end;
		}
		tmax = tsave;
		for (;;) {
			double f0 = Pitch_getValueAtTime (pitch, tmax, kPitch_unit_HERTZ, Pitch_LINEAR);
			if (f0 == NUMundefined) break;
			tmax = Sound_findExtremum (sound, tmax + 0.8 / f0, tmax + 1.25 / f0, includeMaxima, includeMinima);
			if (tmax > tright) {
				if (! PointProcess_addPoint (point, tmax)) goto end;
				addedRight = tmax;
				break;
			}
			if (! PointProcess_addPoint (point, tmax)) goto end;
			addedRight = tmax;
		}
		t = tright;
	}
end:
	Melder_progress1 (1.0, NULL);
	iferror forget (point);
	return point;
}
static void copyColumnLabels (TableOfReal me, TableOfReal thee) {
	Melder_assert (me != thee);
	Melder_assert (my numberOfColumns == thy numberOfColumns);
	for (long icol = 1; icol <= my numberOfColumns; icol ++) {
		thy columnLabels [icol] = Melder_wcsdup (my columnLabels [icol]);
	}
}
Example #5
0
void FormantGridEditor_init (FormantGridEditor me, const char32 *title, FormantGrid data) {
	Melder_assert (data != NULL);
	Melder_assert (Thing_member (data, classFormantGrid));
	FunctionEditor_init (me, title, data);
	my ycursor = 0.382 * my p_formantFloor + 0.618 * my p_formantCeiling;
	my selectedFormant = 1;
}
static void copyRowLabels (TableOfReal me, TableOfReal thee) {
	Melder_assert (me != thee);
	Melder_assert (my numberOfRows == thy numberOfRows);
	for (long irow = 1; irow <= my numberOfRows; irow ++) {
		thy rowLabels [irow] = Melder_wcsdup (my rowLabels [irow]);
	}
}
Example #7
0
void Artword_setTarget (Artword me, int feature, double time, double target) {
    try {
        Melder_assert (feature >= 1);
        Melder_assert (feature <= kArt_muscle_MAX);
        ArtwordData f = & my data [feature];
        Melder_assert (f -> numberOfTargets >= 2);
        int insert = 1;
        if (time < 0.0) time = 0.0;
        if (time > my totalTime) time = my totalTime;
        while (insert <= f -> numberOfTargets && f -> times [insert] < time)
            insert ++;
        Melder_assert (insert <= f -> numberOfTargets);   // can never insert past totalTime
        if (f -> times [insert] != time) {
            long numberOfTargets = f -> numberOfTargets;
            NUMvector_insert <double> (& f -> times, 1, & numberOfTargets, insert);
            numberOfTargets = f -> numberOfTargets;
            NUMvector_insert <double> (& f -> targets, 1, & numberOfTargets, insert);
            f -> numberOfTargets ++;
        }
        f -> targets [insert] = target;
        f -> times [insert] = time;
    } catch (MelderError) {
        Melder_throw (me, ": target not set.");
    }
}
Example #8
0
static void putResult (long iframe, long place, int itrack, void *closure) {
	struct fparm *me = (struct fparm *) closure;
	Melder_assert (iframe > 0 && iframe <= my my nx);
	Melder_assert (itrack > 0 && itrack <= 5);
	Melder_assert (place > 0);
	Melder_assert (place <= my my d_frames [iframe]. nFormants);
	my thy d_frames [iframe]. formant [itrack] = my my d_frames [iframe]. formant [place];
}
static void copyColumn (TableOfReal me, long myCol, TableOfReal thee, long thyCol) {
	Melder_assert (me != thee);
	Melder_assert (my numberOfRows == thy numberOfRows);
	thy columnLabels [thyCol] = Melder_wcsdup (my columnLabels [myCol]);
	for (long irow = 1; irow <= my numberOfRows; irow ++) {
		thy data [irow] [thyCol] = my data [irow] [myCol];
	}
}
static void copyRow (TableOfReal me, long myRow, TableOfReal thee, long thyRow) {
	Melder_assert (me != thee);
	Melder_assert (my numberOfColumns == thy numberOfColumns);
	thy rowLabels [thyRow] = Melder_wcsdup (my rowLabels [myRow]);
	for (long icol = 1; icol <= my numberOfColumns; icol ++) {
		thy data [thyRow] [icol] = my data [myRow] [icol];
	}
}
Example #11
0
Sound Sound_createSimple (long numberOfChannels, double duration, double samplingFrequency) {
	Melder_assert (duration >= 0.0);
	Melder_assert (samplingFrequency > 0.0);
	double numberOfSamples_f = round (duration * samplingFrequency);
	if (numberOfSamples_f > (double) INT32_MAX)
		Melder_throw (U"Cannot create sounds with more than ", Melder_bigInteger (INT32_MAX), U" samples, because they cannot be saved to disk.");
	return Sound_create (numberOfChannels, 0.0, duration, (long) (int32_t) numberOfSamples_f,
		1 / samplingFrequency, 0.5 / samplingFrequency);
}
Example #12
0
autoComplexSpectrogram Sound_to_ComplexSpectrogram (Sound me, double windowLength, double timeStep) {
	try {
		double samplingFrequency = 1.0 / my dx, myDuration = my xmax - my xmin, t1;
		if (windowLength > myDuration) {
			Melder_throw (U"Your sound is too short:\nit should be at least as long as one window length.");
		}
		
		long nsamp_window = (long) floor (windowLength / my dx);
		long halfnsamp_window = nsamp_window / 2 - 1;
		nsamp_window = halfnsamp_window * 2;
		
		if (nsamp_window < 2) {
			Melder_throw (U"Your analysis window is too short: less than two samples.");
		}
		
		long numberOfFrames;
		Sampled_shortTermAnalysis (me, windowLength, timeStep, &numberOfFrames, &t1);

		// Compute sampling of the spectrum

		long numberOfFrequencies = halfnsamp_window + 1;
		double df = samplingFrequency / (numberOfFrequencies - 1);
		
		autoComplexSpectrogram thee = ComplexSpectrogram_create (my xmin, my xmax, numberOfFrames, timeStep, t1, 0.0, 0.5 * samplingFrequency, numberOfFrequencies, df, 0.0);
		// 
		autoSound analysisWindow = Sound_create (1, 0.0, nsamp_window * my dx, nsamp_window, my dx, 0.5 * my dx);
		
		for (long iframe = 1; iframe <= numberOfFrames; iframe++) {
			double t = Sampled_indexToX (thee.get(), iframe);
			long leftSample = Sampled_xToLowIndex (me, t), rightSample = leftSample + 1;
			long startSample = rightSample - halfnsamp_window;
			long endSample = leftSample + halfnsamp_window;
			Melder_assert (startSample >= 1);
			Melder_assert (endSample <= my nx);
			
			for (long j = 1; j <= nsamp_window; j++) {
				analysisWindow -> z[1][j] = my z[1][startSample - 1 + j];
			}
			// window ?
			autoSpectrum spec = Sound_to_Spectrum (analysisWindow.get(), 0);
			
			thy z[1][iframe] = spec -> z[1][1] * spec -> z[1][1];
			thy phase[1][iframe] = 0.0;
			for (long ifreq = 2; ifreq <= numberOfFrequencies - 1; ifreq++) {
				double x = spec -> z[1][ifreq], y = spec -> z[2][ifreq];
				thy z[ifreq][iframe] = x * x + y * y; // power
				thy phase[ifreq][iframe] = atan2 (y, x); // phase [-pi,+pi]
			}
			// even number of samples
			thy z[numberOfFrequencies][iframe] = spec -> z[1][numberOfFrequencies] * spec -> z[1][numberOfFrequencies];
			thy phase[numberOfFrequencies][iframe] = 0.0;
		}
		return thee;
	} catch (MelderError) {
		Melder_throw (me, U": no ComplexSpectrogram created.");
	}
}
Example #13
0
void Graphics_setWindow (Graphics me, double x1WC, double x2WC, double y1WC, double y2WC) {
	Melder_assert (x1WC != x2WC);
	Melder_assert (y1WC != y2WC);
	my d_x1WC = x1WC;
	my d_x2WC = x2WC;
	my d_y1WC = y1WC;
	my d_y2WC = y2WC;
	computeTrafo (me);
	if (my recording)
		{ op (SET_WINDOW, 4); put (x1WC); put (x2WC); put (y1WC); put (y2WC); }
}
void Sampled_shortTermAnalysis (Sampled me, double windowDuration, double timeStep, long *numberOfFrames, double *firstTime) {
	Melder_assert (windowDuration > 0.0);
	Melder_assert (timeStep > 0.0);
	volatile double myDuration = my dx * my nx;
	if (windowDuration > myDuration)
		Melder_throw (me, ": shorter than window length."); 
	*numberOfFrames = floor ((myDuration - windowDuration) / timeStep) + 1;
	Melder_assert (*numberOfFrames >= 1);
	double ourMidTime = my x1 - 0.5 * my dx + 0.5 * myDuration;
	double thyDuration = *numberOfFrames * timeStep;
	*firstTime = ourMidTime - 0.5 * thyDuration + 0.5 * timeStep;
}
Example #15
0
static void burg (double sample [], long nsamp_window, double cof [], int nPoles,
	Formant_Frame frame, double nyquistFrequency, double safetyMargin)
{
	double a0;
	NUMburg (sample, nsamp_window, cof, nPoles, & a0);

	/*
	 * Convert LP coefficients to polynomial.
	 */
	autoPolynomial polynomial = Polynomial_create (-1, 1, nPoles);
	for (int i = 1; i <= nPoles; i ++)
		polynomial -> coefficients [i] = - cof [nPoles - i + 1];
	polynomial -> coefficients [nPoles + 1] = 1.0;

	/*
	 * Find the roots of the polynomial.
	 */
	autoRoots roots = Polynomial_to_Roots (polynomial.peek());
	Roots_fixIntoUnitCircle (roots.peek());

	Melder_assert (frame -> nFormants == 0 && ! frame -> formant);

	/*
	 * First pass: count the formants.
	 * The roots come in conjugate pairs, so we need only count those above the real axis.
	 */
	for (int i = roots -> min; i <= roots -> max; i ++) if (roots -> v [i]. im >= 0) {
		double f = fabs (atan2 (roots -> v [i].im, roots -> v [i].re)) * nyquistFrequency / NUMpi;
		if (f >= safetyMargin && f <= nyquistFrequency - safetyMargin)
			frame -> nFormants ++;
	}

	/*
	 * Create space for formant data.
	 */
	if (frame -> nFormants > 0)
		frame -> formant = NUMvector <structFormant_Formant> (1, frame -> nFormants);

	/*
	 * Second pass: fill in the formants.
	 */
	int iformant = 0;
	for (int i = roots -> min; i <= roots -> max; i ++) if (roots -> v [i]. im >= 0.0) {
		double f = fabs (atan2 (roots -> v [i].im, roots -> v [i].re)) * nyquistFrequency / NUMpi;
		if (f >= safetyMargin && f <= nyquistFrequency - safetyMargin) {
			Formant_Formant formant = & frame -> formant [++ iformant];
			formant -> frequency = f;
			formant -> bandwidth = -
				log (roots -> v [i].re * roots -> v [i].re + roots -> v [i].im * roots -> v [i].im) * nyquistFrequency / NUMpi;
		}
	}
	Melder_assert (iformant == frame -> nFormants);   // may fail if some frequency is NaN
}
Example #16
0
	static gboolean _GuiWindow_resizeCallback (GuiObject widget, GtkAllocation *allocation, gpointer void_me) {
		(void) widget;
		iam (GuiWindow);
		trace ("fixed received size allocation: (%ld, %ld), %ld x %ld.", (long) allocation -> x, (long) allocation -> y, (long) allocation -> width, (long) allocation -> height);
		if (allocation -> width != my d_width || allocation -> height != my d_height) {
			trace ("user changed the size of the window?");
			/*
			 * Apparently, GTK sends the size allocation message both to the shell and to its fixed-container child.
			 * we could capture the message either from the shell or from the fixed; we choose to do it from the fixed.
			 */
			Melder_assert (GTK_IS_FIXED (widget));
			/*
			 * We move and resize all the children of the fixed.
			 */
			GList *children = GTK_FIXED (widget) -> children;
			for (GList *l = g_list_first (children); l != NULL; l = g_list_next (l)) {
				GtkFixedChild *listElement = (GtkFixedChild *) l -> data;
				GtkWidget *childWidget = listElement -> widget;
				Melder_assert (childWidget);
				Thing_cast (GuiThing, child, _GuiObject_getUserData (childWidget));
				if (child) {
					GuiControl control = NULL;
					if (Thing_member (child, classGuiControl)) {
						control = static_cast <GuiControl> (child);
					} else if (Thing_member (child, classGuiMenu)) {
						Thing_cast (GuiMenu, menu, child);
						control = menu -> d_cascadeButton;
					}
					if (control) {
						/*
						 * Move and resize.
						 */
						trace ("moving child of class %ls", Thing_className (control));
						int left = control -> d_left, right = control -> d_right, top = control -> d_top, bottom = control -> d_bottom;
						if (left   <  0) left   += allocation -> width;   // this replicates structGuiControl :: v_positionInForm ()
						if (right  <= 0) right  += allocation -> width;
						if (top    <  0) top    += allocation -> height;
						if (bottom <= 0) bottom += allocation -> height;
						trace ("moving child to (%d,%d)", left, top);
						gtk_fixed_move (GTK_FIXED (widget), GTK_WIDGET (childWidget), left, top);
						gtk_widget_set_size_request (GTK_WIDGET (childWidget), right - left, bottom - top);
						trace ("moved child of class %ls", Thing_className (control));
					}
				}
			}
			my d_width = allocation -> width;
			my d_height = allocation -> height;
			gtk_widget_set_size_request (GTK_WIDGET (widget), allocation -> width, allocation -> height);
		}
		trace ("end");
		return FALSE;
	}
void FormantGridEditor_init (FormantGridEditor me, GuiObject parent, const wchar *title, FormantGrid data) {
	Melder_assert (data != NULL);
	Melder_assert (Thing_member (data, classFormantGrid));
	FunctionEditor_init (me, parent, title, data);
	my formantFloor = preferences.formantFloor;
	my formantCeiling = preferences.formantCeiling;
	my bandwidthFloor = preferences.bandwidthFloor;
	my bandwidthCeiling = preferences.bandwidthCeiling;
	my play = preferences.play;
	my source = preferences.source;
	my ycursor = 0.382 * my formantFloor + 0.618 * my formantCeiling;
	my selectedFormant = 1;
}
Example #18
0
static double Sound_findExtremum (Sound me, double tmin, double tmax, int includeMaxima, int includeMinima) {
	long imin = Sampled_xToLowIndex (me, tmin), imax = Sampled_xToHighIndex (me, tmax);
	double iextremum;
	Melder_assert (NUMdefined (tmin));
	Melder_assert (NUMdefined (tmax));
	if (imin < 1) imin = 1;
	if (imax > my nx) imax = my nx;
	iextremum = findExtremum_3 (my z [1], my ny > 1 ? my z [2] : NULL, imin - 1, imax - imin + 1, includeMaxima, includeMinima);
	if (iextremum)
		return my x1 + (imin - 1 + iextremum - 1) * my dx;
	else
		return (tmin + tmax) / 2;
}
Example #19
0
const char * Melder8_fixed (double value, int precision) {
	int minimumPrecision;
	if (value == NUMundefined) return "--undefined--";
	if (value == 0.0) return "0";
	if (++ ibuffer == NUMBER_OF_BUFFERS) ibuffer = 0;
	if (precision > 60) precision = 60;
	minimumPrecision = - (int) floor (log10 (fabs (value)));
	int n = snprintf (buffers8 [ibuffer], MAXIMUM_NUMERIC_STRING_LENGTH + 1, "%.*f",
		minimumPrecision > precision ? minimumPrecision : precision, value);
	Melder_assert (n > 0);
	Melder_assert (n <= MAXIMUM_NUMERIC_STRING_LENGTH);
	return buffers8 [ibuffer];
}
Example #20
0
static double getLocalCost (long iframe, long icand, int itrack, void *closure) {
	struct fparm *me = (struct fparm *) closure;
	Formant_Frame frame = & my my d_frames [iframe];
	Formant_Formant candidate;
	if (icand > frame -> nFormants) return 1e30;
	candidate = & frame -> formant [icand];
	/*if (candidate -> frequency <= 0.0) candidate -> frequency = 0.001;
		Melder_fatal (U"Weird formant frequency ", candidate -> frequency, U" Hz.")*/;
	Melder_assert (candidate -> bandwidth > 0.0);
	Melder_assert (itrack > 0 && itrack <= 5);
	return my dfCost * fabs (candidate -> frequency - my refF [itrack]) +
		my bfCost * candidate -> bandwidth / candidate -> frequency;
}
Example #21
0
long KNN_prune_kCoverage
(
    ///////////////////////////////
    // Parameters                //
    ///////////////////////////////

    Pattern p,      // source
    //
    Categories c,   // source
    //
    long y,         // source instance index
    //
    long k,         // k(!)
    //
    long * indices  // Out: kCoverage set
    //
)

{
    Melder_assert(y <= p->ny);
    Melder_assert(k > 0 && k <= p->ny);

    long cc = 0;
    FeatureWeights fws = FeatureWeights_create(p->nx);

    if (fws)
    {
        long *tempindices = NUMlvector (0, p->ny - 1);
        for (long yy = 1; yy <= p->ny; yy++)
        {
            if (y != yy && FRIENDS(c->item[y], c->item[yy]))
            {
                // long n = KNN_kNeighboursSkip(p, p, fws, yy, k, tempindices, 0); .OS.081011
                long n = KNN_kNeighboursSkip(p, p, fws, yy, k, tempindices, y);
                while (n)
                {
                    Melder_assert (n <= p->ny);
                    if (tempindices[--n] == y)
                    {
                        indices[cc++] = yy;
                        break;
                    }
                }
            }
        }
        NUMlvector_free (tempindices, 0);
        forget(fws);
    }
    return(cc);
}
Example #22
0
double RealTier_getStandardDeviation_curve (RealTier me, double tmin, double tmax) {
	long n = my points.size, imin, imax;
	double mean, integral = 0.0;
	if (tmax <= tmin) { tmin = my xmin; tmax = my xmax; }   // autowindow
	if (n == 0) return NUMundefined;
	if (n == 1) return 0.0;
	imin = AnyTier_timeToLowIndex (me->asAnyTier(), tmin);
	if (imin == n) return 0.0;
	imax = AnyTier_timeToHighIndex (me->asAnyTier(), tmax);
	if (imax == 1) return 0.0;
	Melder_assert (imin < n);
	Melder_assert (imax > 1);
	/*
	 * Add the areas between the points.
	 * This works even if imin is 0 (offleft) and/or imax is n + 1 (offright).
	 */
	mean = RealTier_getMean_curve (me, tmin, tmax);
	for (long i = imin; i < imax; i ++) {
		double tleft, fleft, tright, fright, sum, diff;
		if (i == imin) {
			tleft = tmin;
			fleft = RealTier_getValueAtTime (me, tmin);
		} else {
			tleft = my points.at [i] -> number;
			fleft = my points.at [i] -> value - mean;
		}
		if (i + 1 == imax) {
			tright = tmax;
			fright = RealTier_getValueAtTime (me, tmax);
		} else {
			tright = my points.at [i + 1] -> number;
			fright = my points.at [i + 1] -> value - mean;
		}
		/*
		 * The area is integral dt f^2
		 *   = integral dt [f1 + (f2-f1)/(t2-t1) (t-t1)]^2
		 *   = int dt f1^2 + int dt 2 f1 (f2-f1)/(t2-t1) (t-t1) + int dt [(f2-f1)/(t2-t1)]^2 (t-t1)^2
		 *   = f1^2 (t2-t1) + f1 (f2-f1)/(t2-t1) (t2-t1)^2 + 1/3 [(f2-f1)/(t2-t1)]^2 (t2-t1)^3
		 *   = (t2-t1) [f1 f2 + 1/3 (f2-f1)^2]
		 *   = (t2-t1) (f1^2 + f2^2 + 1/3 f1 f2)
		 *   = (t2-t1) [1/4 (f1+f2)^2 + 1/12 (f1-f2)^2]
		 * In the last expression, we have a sum of squares, which is computationally best.
		 */
		sum = fleft + fright;
		diff = fleft - fright;
		integral += (sum * sum + (1.0/3.0) * diff * diff) * (tright - tleft);
	}
	return sqrt (0.25 * integral / (tmax - tmin));
}
Example #23
0
long PointProcess_getLowIndex (PointProcess me, double t) {
	if (my nt == 0 || t < my t [1])
		return 0;
	if (t >= my t [my nt])   // special case that often occurs in practice
		return my nt;
	Melder_assert (my nt != 1);   // may fail if t or my t [1] is NaN
	/* Start binary search. */
	long left = 1, right = my nt;
	while (left < right - 1) {
		long mid = (left + right) / 2;
		if (t >= my t [mid]) left = mid; else right = mid;
	}
	Melder_assert (right == left + 1);
	return left;
}
Example #24
0
int Sampled_shortTermAnalysis (I, double windowDuration, double timeStep, long *numberOfFrames, double *firstTime) {
	iam (Sampled);
	double myDuration, thyDuration, ourMidTime;
	Melder_assert (windowDuration > 0.0);
	Melder_assert (timeStep > 0.0);
	myDuration = my dx * my nx;
	if (windowDuration > myDuration)
		return Melder_error2 (Thing_className (me), L" shorter than window length."); 
	*numberOfFrames = floor ((myDuration - windowDuration) / timeStep) + 1;
	Melder_assert (*numberOfFrames >= 1);
	ourMidTime = my x1 - 0.5 * my dx + 0.5 * myDuration;
	thyDuration = *numberOfFrames * timeStep;
	*firstTime = ourMidTime - 0.5 * thyDuration + 0.5 * timeStep;
	return 1;
}
MFCC MelFilter_to_MFCC (MelFilter me, long numberOfCoefficients) {
	try {
		autoNUMmatrix<double> cosinesTable (NUMcosinesTable (my ny), 1, 1);
		autoNUMvector<double> x (1, my ny);
		autoNUMvector<double> y (1, my ny);
		
		double fmax_mel = my y1 + (my ny - 1) * my dy;
		numberOfCoefficients = numberOfCoefficients > my ny - 1 ? my ny - 1 : numberOfCoefficients;
		Melder_assert (numberOfCoefficients > 0);
		// 20130220 new interpretation of maximumNumberOfCoefficients necessary for inverse transform 
		autoMFCC thee = MFCC_create (my xmin, my xmax, my nx, my dx, my x1, my ny - 1, my ymin, my ymax);
		for (long frame = 1; frame <= my nx; frame++) {
			CC_Frame cf = (CC_Frame) & thy frame[frame];
			for (long i = 1; i <= my ny; i++) {
				x[i] = my z[i][frame];
			}
			NUMcosineTransform (x.peek(), y.peek(), my ny, cosinesTable.peek());
			CC_Frame_init (cf, numberOfCoefficients);
			for (long i = 1; i <= numberOfCoefficients; i++) {
				cf -> c[i] = y[i + 1];
			}
			cf -> c0 = y[1];
		}
		return thee.transfer();
	} catch (MelderError) {
		Melder_throw (me, ": no MFCC created.");
	}
}
Example #26
0
Ltas Matrix_to_Ltas (Matrix me) {
	Ltas thee = (structLtas *)Data_copy (me);
	if (! thee) return NULL;
	Melder_assert (sizeof (struct structLtas) == sizeof (struct structMatrix));
	Thing_overrideClass (thee, classLtas);
	return thee;
}
Example #27
0
	static gboolean _GuiGtkDrawingArea_exposeCallback (GuiObject widget, GdkEventExpose *expose, gpointer void_me) {
		trace (U"begin");
		iam (GuiDrawingArea);
		Melder_assert (me);
		// TODO: that helps against the damaged regions outside the rect where the
		// Graphics drawing is done, but where does that margin come from in the
		// first place?? Additionally this causes even more flickering
		//gdk_window_clear_area ((GTK_WIDGET (widget)) -> window, expose->area.x, expose->area.y, expose->area.width, expose->area.height);
		if (my d_exposeCallback) {
			struct structGuiDrawingArea_ExposeEvent event { me, 0 };
			event. x = expose -> area. x;
			event. y = expose -> area. y;
			event. width = expose -> area. width;
			event. height = expose -> area. height;
			try {
				//GdkRectangle rect = { event. x, event. y, event. width, event. height };
				//gdk_window_begin_paint_rect ((GTK_WIDGET (widget)) -> window, & rect);
				trace (U"send the expose callback");
				trace (U"locale is ", Melder_peek8to32 (setlocale (LC_ALL, nullptr)));
				my d_exposeCallback (my d_exposeBoss, & event);
				trace (U"the expose callback finished");
				trace (U"locale is ", Melder_peek8to32 (setlocale (LC_ALL, nullptr)));
				//gdk_window_end_paint ((GTK_WIDGET (widget)) -> window);
				//gdk_window_flush ((GTK_WIDGET (widget)) -> window);
				//gdk_flush ();
			} catch (MelderError) {
				Melder_flushError (U"Redrawing not completed");
			}
			trace (U"the expose callback handled drawing");
			return true;
		}
		trace (U"GTK will handle redrawing");
		return false;
	}
static void do_oops (RunnerMFC me) {
	ExperimentMFC experiment = (ExperimentMFC) my data;
	Melder_assert (experiment -> trial >= 2 && experiment -> trial <= experiment -> numberOfTrials + 1);
	if (experiment -> trial <= experiment -> numberOfTrials) {
		experiment -> responses [experiment -> trial] = 0;
		experiment -> goodnesses [experiment -> trial] = 0;
	}
	experiment -> trial --;
	experiment -> responses [experiment -> trial] = 0;
	experiment -> goodnesses [experiment -> trial] = 0;
	experiment -> pausing = FALSE;
	my numberOfReplays = 0;
	my broadcastDataChanged ();
	if (experiment -> blankWhilePlaying) {
		Graphics_setGrey (my graphics, 0.8);
		Graphics_fillRectangle (my graphics, 0, 1, 0, 1);
		Graphics_setGrey (my graphics, 0.0);
		Graphics_flushWs (my graphics);
	}
	Graphics_updateWs (my graphics);
	if (experiment -> stimuliAreSounds) {
		autoMelderAudioSaveMaximumAsynchronicity saveMaximumAsynchronicity;
		if (experiment -> blankWhilePlaying)
			MelderAudio_setOutputMaximumAsynchronicity (kMelder_asynchronicityLevel_SYNCHRONOUS);
		ExperimentMFC_playStimulus (experiment, experiment -> stimuli [experiment -> trial]);
	}
}
Example #29
0
void Pitch_step (Pitch me, double step, double precision, double tmin, double tmax) {
	Melder_assert (precision >= 0.0 && precision < 1.0);
	long imin, imax;
	if (! Sampled_getWindowSamples (me, tmin, tmax, & imin, & imax)) return;
	for (long i = imin; i <= imax; i ++) {
		Pitch_Frame frame = & my frame [i];
		double currentFrequency = frame -> candidate [1]. frequency;
		if (currentFrequency > 0.0 && currentFrequency < my ceiling) {
			double targetFrequency = currentFrequency * step;
			double fmin = (1 - precision) * targetFrequency;
			double fmax = (1 + precision) * targetFrequency;
			int icand, nearestCandidate = 0;
			double nearestDistance = my ceiling;
			if (fmax > my ceiling) fmax = my ceiling;
			for (icand = 2; icand <= frame -> nCandidates; icand ++) {
				double f = frame -> candidate [icand]. frequency;
				if (f > fmin && f < fmax) {
					double localDistance = fabs (f - targetFrequency);
					if (localDistance < nearestDistance) {
						nearestCandidate = icand;
						nearestDistance = localDistance;
					}
				}
			}
			if (nearestCandidate) {   /* Swap candidates. */
				struct structPitch_Candidate candidate = frame -> candidate [nearestCandidate];
				frame -> candidate [nearestCandidate] = frame -> candidate [1];
				frame -> candidate [1] = candidate;
			}
		}
	}
}
Example #30
0
void Permutation_swapNumbers (Permutation me, long i1, long i2) {
	try {
		long ip = 0;
		if (i1 < 1 || i1 > my numberOfElements || i2 < 1 || i2 > my numberOfElements) {
			Melder_throw ("");
		}
		if (i1 == i2) {
			return;
		}
		for (long i = 1; i <= my numberOfElements; i++) {
			if (my p[i] == i1) {
				my p[i] = i2;
				ip++;
			} else if (my p[i] == i2) {
				my p[i] = i1;
				ip++;
			}
			if (ip == 2) {
				break;
			}
		}
		Melder_assert (ip == 2);
	} catch (MelderError) {
		Melder_throw (me, ": numbers not swapped.");
	}
}