예제 #1
0
//===========================================================================
void Tform_Main::run_FFT ( CCollection<short int> *in, CCollectionStorage<float>  *fft, float *CentralFreq, float minFreq, float maxFreq )
{
    int aPower;
    CCollection<float> re; re.Clear();
    CCollection<float> im; im.Clear();

    int counter = 0;
    int MaximumIndex = -1;
    float temp;
    SoundData.Get_Maximum_ext(&temp, &MaximumIndex);

    for ( unsigned int i = MaximumIndex; i < SoundData.ValuesCount; i++) {
        re.Add(SoundData.Values[i]);
        //re.Add(LoadedData.Items[1]->Values[i]);
        im.Add(0);
        if ( counter++ > 263144 ) break; /// --- Если больше 2 ^18 ----
    }

    // ******************
        FFT(&re, &im, &aPower);
    // ******************

// -----
    fft->SetItemsCount(2);
     int DataCount = exp(aPower * std::log(2.0));
     for ( int i = 0; i < DataCount / 2; i++)
     {
         double xVal = i / (double)DataCount * WorkFreq;
         if ( xVal >= minFreq && xVal < maxFreq )
         {
             double yVal = sqrt(re.Values[i]*re.Values[i] + im.Values[i]*im.Values[i])*2.0 / (double)DataCount;
             fft->Items[0]->Add(xVal);
             fft->Items[1]->Add(yVal);
         }

    }

//    int   array_index = -1;
//      float array_value = -1;
//    fft->Items[1]->Get_Maximum_ext(&array_value, &array_index);
//    *CentralFreq = fft->Items[0]->Values[array_index];
}
예제 #2
0
//===========================================================================
void __fastcall TfrmMain::bAddCanalsClick(TObject *Sender)
{
    int ButtonTag = ((TButton*)Sender)->Tag;
    if ( CheckListBox1->Items->Count == 0 ) return;
    int CountCheckedItems = 0;
    for ( int i = 0; i < CheckListBox1->Items->Count; i++ )
        if ( CheckListBox1->Checked[i] == true ) CountCheckedItems++;

    if (  CountCheckedItems != 2 )
    {
        MessageBox(NULL, "Выберите два сигнала для проведения операции", "Signal - Ошибка", MB_OK|MB_ICONERROR|MB_TASKMODAL);
        return;
    }

    // ----- Количество выделенных елементов ---------
    CurrentWorkDevice->Canals->Add();
    CCollection<short int> *BaseCol = NULL;;
    CCollection<short int> *SecondCol  = NULL;;
    CCollection<short int> *NewCol  = CurrentWorkDevice->Canals->Items[CurrentWorkDevice->Canals->ItemsCount - 1];

    short int *Base    = NULL;
    short int *Second  = NULL;
    // -----
    for ( int i = 0; i < CheckListBox1->Items->Count; i++ )
        if ( CheckListBox1->Checked[i] == true )
        {
            if ( Base == NULL )
            {
                 BaseCol = (CCollection<short int> *)CheckListBox1->Items->Objects[i];
                 Base    = BaseCol->Values;
            }
            else
            {
                SecondCol = (CCollection<short int> *)CheckListBox1->Items->Objects[i];
                Second = SecondCol->Values;
            }
        }
    // -----
    NewCol->ValueT0                = BaseCol->ValueT0;
    NewCol->gr_YVoltTransformCoef  = BaseCol->gr_YVoltTransformCoef;
    // -----
    int CountData = ((CCollection<short int> *)CheckListBox1->Items->Objects[0])->Count;
    char *val = (char*) malloc (100);
    if (  ButtonTag == 0 )
    {
        for ( int i = 0; i < CountData; i++ )NewCol->Add(Base[i] + Second[i]);
        sprintf (val, "%s_p_%s", BaseCol->Name, SecondCol->Name);
    }
    else
    {
        for ( int i = 0; i < CountData; i++ )NewCol->Add(Base[i] - Second[i]);
        sprintf (val, "%s_m_%s", BaseCol->Name, SecondCol->Name);
    }
    NewCol->SetName(val);
    free(val);


    SetInterfaceParam();
    Application->ProcessMessages();
    rgVoltScalesClick(Sender);
    rgTimeScalesClick(Sender);
    // -----
    BChart->DrawSeriesValues();
    BChart->Canals = BChart->Canals;
    BChart->pbMain->Repaint();
    Application->ProcessMessages();
    // -----
    bAutoPositionClick(Sender);

}
예제 #3
0
//===========================================================================
void __fastcall Tform_Main::button_StartDTFCalcClick1(TObject *Sender)
{
    DecimalSeparator = '.';

    if ( listbox_DTFFreqs->Items->Count != 0 )
        if ( listbox_DTFFreqs->ItemIndex != -1 )
            ResonatorFreq = StrToFloat(listbox_DTFFreqs->Items->Strings[listbox_DTFFreqs->ItemIndex]);

    PageControl1->TabIndex = 3;
    PageControl2->TabIndex = 0;
    Application->ProcessMessages();

    ClearSeries(Chart2, true);
    Chart2->AutoSize = true;
    // -----------------------------------------
    AddStringToLog("DFT Calculate");
   // -----------------------------------------

        // -----------
        float Freq1 = 0;
        float Freq2 = 0;
        try {
            Freq1 = StrToFloat( e_Freq1->Text );
            Freq2 = StrToFloat( e_Freq2->Text );
        } catch (...)
        {
            MessageBox(Handle, "Ошибка ввода диапазона частот", "Ошибка", 0);
            return;
        }

        // ----------- Чарт -----------
        ClearSeries(Chart2, true);

        button_StartDTFCalc->Enabled = false;
        button_StopDTFCalc ->Enabled = true;
        isDTFStoped = false;

////////////////////////////////
/*
        SoundData.Clear();
        Freq1 = 5929.56;
        Freq2 = 5932.56;
        WorkFreq = 48000;
        for ( int i = 0; i < 500000; i++)
            SoundData.Add(10000.0 * sin(TWO_PI*5931.06*i / (float)WorkFreq));
*/
////////////////////////////////

        // --------------
///////////////
        int CountData = SoundData.ValuesCount;
        float *x_r  = (float*) malloc (sizeof(float) * CountData);
        float  s_r;
        float  s_i;
        float  t_r;
        float  t_i;

        for ( int i = 0; i < CountData; i++)
            x_r[i] = SoundData.Values[i];

        // -------------
        int    Mode =  0;  // ----- Прямое преобразование фурье ----
        float S    = -1; // ---- Прямое или обратное (-1 / 1) преобразование
        //float R    =  1; // ----

        if ( Mode == 1 )
        {
         S = 1.0;
         //R = 1.0 / (float)CountData;
        }
        CCollection<float> xFreqValues;  xFreqValues.Clear();
        CCollection<float> yFreqValues;  yFreqValues.Clear();

        // ------------- Индексы масивов , для которых будем  считать ДПФ -----
///////////////
        int i1 = (CountData) * Freq1 / WorkFreq;
        int i2 = (CountData) * Freq2 / WorkFreq;

        // -------------
        Chart2->BottomAxis->SetMinMax(i1 / (float) CountData * WorkFreq, i2 / (float)CountData * WorkFreq);
        float CountData_inv = 1.0 / (float)CountData;
        float S_TWO_PI_CountData_inv = S*TWO_PI*CountData_inv;

        float max = -121312;
        int   max_index = -1;

        for (int k = i1; k < i2; k++ )
        {
            if ( isDTFStoped == true ) break;

                s_i = 0;
                s_r = 0;
                for ( int n = 0; n < CountData; n++ )
                {
                    float argument = S_TWO_PI_CountData_inv * k*n;

                    t_r = cos(argument);
                    t_i = sin(argument);
                    s_r = s_r + x_r[n]*t_r;// - a.i*b.i;
                    s_i = s_i + x_r[n]*t_i;// + a.r*b.i;
                }
                float x_val = k * CountData_inv * WorkFreq;
                float y_val = sqrt(s_r*s_r + s_i*s_i);

                y_val = y_val * 2.0 * CountData_inv;

                if ( max < y_val ){
                    max = y_val;
                    max_index = k;
                }

                xFreqValues.Add(x_val);
                yFreqValues.Add(y_val);

                Chart2->Series[0]->AddXY(x_val, y_val);
                Application->ProcessMessages();
        }

        float index1 = (max_index - 2 < 0 ) ? 0 : max_index - 2;
        float index2 = (max_index + 2 > CountData - 1 ) ? CountData - 1 : max_index + 2;
        float indexator_incroment = 1.0 / (float)DTF_InterpolationPointsCount;
        for (float k = index1; k < index2; k = k + indexator_incroment )
        {
            if ( isDTFStoped == true ) break;

            s_i = s_r = 0;
            for ( int n = 0; n < CountData; n++ )
            {
                //float argument = k*n * S_TWO_PI_CountData_inv;
                float argument = S_TWO_PI_CountData_inv * k*n;
                t_r = cos(argument);
                t_i = sin(argument);

                s_r = s_r + x_r[n]*t_r;
                s_i = s_i + x_r[n]*t_i;
            }
            float x_val = k * CountData_inv * WorkFreq;
            float y_val = sqrt(s_r*s_r + s_i*s_i);

            y_val = y_val * 2.0 * CountData_inv;

            xFreqValues.Add(x_val);
            yFreqValues.Add(y_val);

            Chart2->Series[0]->AddXY(x_val, y_val);
            Application->ProcessMessages();
        }

        free(x_r);


   // -----------------------------------------
   // -----------------------------------------
   // ----- Расчет добротности ----------------
   // -----------------------------------------
        if ( isDTFStoped == true ){
            AddStringToLog("DFT stoped");
        } else {
            TFastLineSeries *ls = (TFastLineSeries *)Chart2->Series[0];
            float max = -1000;
            float CenterFreq = 0;
            int   Index_of_MaxFreq = -1;

            for ( int i = 0; i < ls->YValues->Count; i++)
                if ( max < ls->YValues->Value[i] ) {
                    max              = ls->YValues->Value[i];
                    CenterFreq       = ls->XValues->Value[i];
                    Index_of_MaxFreq = i;
                }

            float freq1 = 0, freq2 = 0;
            float val1, val2;

            float px_1[2], py_1[2];
            float px_2[2], py_2[2];

            // ---- Поиск Левого бока ----
            for ( int i = Index_of_MaxFreq; i > 1; i-- ) {
                if ( ls->YValues->Value[i] <= 0.707*max)
                {
                    float df = ls->XValues->Value[i+1] - ls->XValues->Value[i];
                    float ya = ls->YValues->Value[i  ];
                    float yb = ls->YValues->Value[i+1];

                    val1  = 0.707*max;
                    freq1 = ls->XValues->Value[i] + df * (0.707*max - ya) / (yb - ya);

                    break;
                }
            }

            // ---- Поиск Правой бока ----
            for ( int i = Index_of_MaxFreq; i < ls->YValues->Count; i++ ) {
                if ( ls->YValues->Value[i] <= 0.707*max)
                {
                    float df = ls->XValues->Value[i  ] - ls->XValues->Value[i-1];
                    float ya = ls->YValues->Value[i-1];
                    float yb = ls->YValues->Value[i  ];

                    val2  = 0.707*max;
                    freq2 = ls->XValues->Value[i-1] + df * (0.707*max - ya) / (yb - ya);

                    break;
                }
            }

/*
Index_of_MaxFreq
*/
/*
            for ( int i = 1; i < ls->YValues->Count; i++)
            {
                if ( ls->YValues->Value[i] >= 0.707*max && freq1 < 100)
                {
                    float df = ls->XValues->Value[i] - ls->XValues->Value[i-1];
                    float ya = ls->YValues->Value[i-1];
                    float yb = ls->YValues->Value[i  ];

                    val1  = 0.707*max;
                    freq1 = ls->XValues->Value[i-1] + df * (0.707*max - ya) / (yb - ya);
                }
                if ( ls->YValues->Value[i] <= 0.707*max && freq1 > 100 && freq2 < 100)
                {
                    float df = ls->XValues->Value[i] - ls->XValues->Value[i-1];
                    float ya = ls->YValues->Value[i-1];
                    float yb = ls->YValues->Value[i  ];

                    val2  = 0.707*max;
                    freq2 = ls->XValues->Value[i-1] + df * (0.707*max - ya) / (yb - ya);
                }
            }
*/
            float q = CenterFreq / (freq2 - freq1);
            AddStringToLog("F/dF = " + FloatToStrF(q, ffFixed, 20, 2));
            e_Dobrotnost2->Text = FloatToStrF(q, ffFixed, 20, 2);
            Chart2->Series[1]->AddXY(CenterFreq, max);
            Chart2->Series[1]->AddXY(freq1, val1);
            Chart2->Series[1]->AddXY(freq2, val2);

            Chart2->Series[2]->AddXY(freq1 - 0.5*(freq2 - freq1), 0.707 * max);
            Chart2->Series[2]->AddXY(freq2 + 0.5*(freq2 - freq1), 0.707 * max);

            Chart2->LeftAxis->SetMinMax(0, max*1.12);
            Chart2->BottomAxis->SetMinMax(freq1 - 2.0*(freq2 - freq1), freq2 + 2.0*(freq2 - freq1));
        }
    // -----------
    button_StartDTFCalc->Enabled = true;
    button_StopDTFCalc ->Enabled = false;
    isDTFStoped = false;
}
예제 #4
0
//===========================================================================
void Tform_Main::GetMaximums( CCollectionStorage<float> *in, CCollectionStorage<float> *out_y, float freq1, float freq2)
{
    if ( in == NULL ) return;
    if ( in->Items == NULL ) return;
    // ФОрмируем масив с реальных максимумов , ищем по производным
        CCollection<float> x, y;

       // -----------
         float differ_old = in->Items[1]->Values[1] - in->Items[1]->Values[0];     // ---- Предыдущая производная  -------
         float differ_cur;                                        // ---- Текущая производная  -------
         for ( unsigned int i = 2; i < in->Items[0]->ValuesCount; i++)
         {
            if ( in->Items[0]->Values[i-1] >= freq1 && in->Items[0]->Values[i-1] <= freq2 )
            {
                differ_cur = in->Items[1]->Values[i] - in->Items[1]->Values[i-1];
                if ( differ_old > 0 && differ_cur < 0 )
                {
                    y.Add(in->Items[1]->Values[i-1]);
                    x.Add(in->Items[0]->Values[i-1]);
                }
                differ_old = differ_cur;
            }
         }


    // теперь с предыдущих максимумов ищу первых N_Maximums максимумов
    int N_Maximums = FFT_MaxPointsCount;

    out_y->Items[0]->Clear();
    out_y->Items[1]->Clear();
    CCollection<int> indexes;

    float max = -1111;
    int   max_index = -1;
    for ( unsigned int i = 0; i < x.ValuesCount; i++ )
    {
        // Прохожусь по запомненым индексам, откидываю повторения
        bool is_index_found = false;
        for ( unsigned int k = 0; k < indexes.ValuesCount; k++ )
            if ( (int ) i == indexes.Values[k] ) is_index_found = true;
        if ( is_index_found == true ) continue;

        // фиксирую максимум
        if ( max < y.Values[i] ) {
            max_index = i;
            max       = y.Values[i];
        }

        // если дошел до конца масива, акамулирую данные
        if ( (unsigned int)i >= x.ValuesCount-1 ){
            out_y->Items[0]->Add(x.Values[max_index]);
            out_y->Items[1]->Add(y.Values[max_index]);
            indexes.Add(max_index);

            i = 0;
            max = -1111;
            max_index = -1;

            // если нашел больше четырех максимумов, валю от сюда )
            if ( indexes.ValuesCount >= (unsigned int)N_Maximums ) break;
        }
    }

}
예제 #5
0
//===========================================================================
void __fastcall TfrmResult_3::BitBtn1Click( TObject *Sender )
{
    CCollection<float> *si_x[3], *si_y[3];
   //-----------
     si_x[0] =  ( cb_Chart1_x->ItemIndex == -1 ) ? NULL : ( CCollection<float> *)cb_Chart1_x->Items->Objects[cb_Chart1_x->ItemIndex];  // ---- частота -----
     si_x[1] =  ( cb_Chart2_x->ItemIndex == -1 ) ? NULL : ( CCollection<float> *)cb_Chart2_x->Items->Objects[cb_Chart2_x->ItemIndex];  // ---- частота -----
     si_x[2] =  ( cb_Chart3_x->ItemIndex == -1 ) ? NULL : ( CCollection<float> *)cb_Chart3_x->Items->Objects[cb_Chart3_x->ItemIndex];  // ---- частота -----

     si_y[0] =  ( cb_Chart1_y->ItemIndex == -1 ) ? NULL : ( CCollection<float> *)cb_Chart1_y->Items->Objects[cb_Chart1_y->ItemIndex];  // ---- Сигнал - Пучности ----
     si_y[1] =  ( cb_Chart2_y->ItemIndex == -1 ) ? NULL : ( CCollection<float> *)cb_Chart2_y->Items->Objects[cb_Chart2_y->ItemIndex];  // ---- Фаза возбуждения ----
     si_y[2] =  ( cb_Chart3_y->ItemIndex == -1 ) ? NULL : ( CCollection<float> *)cb_Chart3_y->Items->Objects[cb_Chart3_y->ItemIndex];  // ---- Фаза Узла ----
     
   //-----------
     double  FreqMaximum       = 0;
     double  Puchnost          = 0;

     double  Dobrotnost        = 0;
     //double  Napjazhenije_Uzla = 0;
     double  FazaPuchnosti     = 0;
   //-----------

     Memo1->Clear();
     int IndexMaximumFreq = -1;
     int MaximumIndex2    = -1;

   //-----------
     Draw_ChartSeries(Chart1, 0, CheckBox1->Checked, true, 3000, 0, 0, si_x[0]->ValuesCount, si_x[0], si_y[0]);
     Draw_ChartSeries(Chart2, 0, CheckBox1->Checked, true, 3000, 0, 0, si_x[1]->ValuesCount, si_x[1], si_y[1]);
     Draw_ChartSeries(Chart3, 0, CheckBox1->Checked, true, 3000, 0, 0, si_x[2]->ValuesCount, si_x[2], si_y[2]);

   //----------- Расчеты ------------
   // ---------- Pасчет данных для определения добротности Резонатора (Ищу максимум на кривой и индекс данных) -----------

     if ( si_x[0] != NULL && si_y[0] != NULL)
     {
               CCollection<float> NormValues;
               float max = si_y[0]->Values[0];

           // ---------
               for ( unsigned int i = 1; i < si_y[0]->ValuesCount; i++, NormValues.Add(si_y[0]->Values[i]))
                     if ( max < si_y[0]->Values[i] ) {
                        max           = si_y[0]->Values[i];
                        IndexMaximumFreq = i;
                     }

           // --------- Нормирую значения -----------
             for ( unsigned int i = 0; i < NormValues.ValuesCount; i++) NormValues.Values[i] = NormValues.Values[i] / max;

           // --------- Ищу индексы на уровне 0.7 -----------
             int i1 = -1, i2 = -1;
             if ( IndexMaximumFreq >= 0)
             {
                 int CurPosition = IndexMaximumFreq;  while ( CurPosition-- >=                           0) if ( NormValues.Values[CurPosition] <  0.7) { i1 = CurPosition; break; }
                     CurPosition = IndexMaximumFreq;  while ( CurPosition++ < (int) NormValues.ValuesCount) if ( NormValues.Values[CurPosition] <  0.7) { i2 = CurPosition; break; }
             }

             float deltaF = (i1 >= 0 && i2 >= 0) ? fabs(si_x[0]->Values[i2] - si_x[0]->Values[i1]) : 0;

             FreqMaximum = (IndexMaximumFreq == 0 ) ? 0 : si_x[0]->Values[IndexMaximumFreq];
             Puchnost    = (IndexMaximumFreq == 0 ) ? 0 : si_y[0]->Values[IndexMaximumFreq]*1000.0;
             Dobrotnost  = ( deltaF          == 0 ) ? 0 : FreqMaximum / deltaF;

           // --------- 
             Memo1->Lines->Add("");  Memo1->Lines->Add("Добротность = " +  FloatToStrF(Dobrotnost, ffFixed, 20, 6));
             Memo1->Lines->Add("");  Memo1->Lines->Add("Частота = " +  FloatToStrF(FreqMaximum, ffFixed, 20, 6));
             Memo1->Lines->Add("");  Memo1->Lines->Add("Ширина полосы = " +  FloatToStrF(deltaF, ffFixed, 20, 6));
         Memo1->Lines->Add("");
             Memo1->Lines->Add("");  Memo1->Lines->Add(AnsiString(si_y[0]->Name)+ " = " + FloatToStrF(Puchnost, ffFixed, 20, 3));
     }

   //-----------
     if ( si_x[1] != NULL && si_y[1] != NULL && IndexMaximumFreq != -1)
     {
         FazaPuchnosti = (IndexMaximumFreq == 0 ) ? 0 : si_y[1]->Values[IndexMaximumFreq]*1000.0;

         Memo1->Lines->Add(AnsiString(si_y[1]->Name) + " = "  + FloatToStrF(FazaPuchnosti, ffFixed, 20, 6));
         Memo1->Lines->Add("");
     }

   //-----------
     if ( si_x[2] != NULL && si_y[2] != NULL)
     {
           float max = si_y[2]->Values[0];
        // ----------
           for ( unsigned int i = 1; i < si_y[2]->ValuesCount; i++)
                 if ( max < si_y[2]->Values[i] ) {
                    max          = si_y[2]->Values[i];
                    MaximumIndex2 = i;
                 }

           if ( MaximumIndex2 != -1 )
           {
               //Napjazhenije_Uzla = si_y[2]->Values[MaximumIndex2]*1000.0;

               Memo1->Lines->Add("");
               //Memo1->Lines->Add(" "  + AnsiString(si_y[2]->Name) + " = " + FloatToStrF(Napjazhenije_Uzla, ffFixed, 20, 3));
               //Memo1->Lines->Add("");
               Memo1->Lines->Add(" Разночастоность = "  + FloatToStrF(fabs(si_x[2]->Values[MaximumIndex2] - FreqMaximum), ffFixed, 20, 6));
           }
         // ----------
     }

  // ----------
         double DeltaFi = ( Puchnost == 0 ) ? 0 : atan2(FazaPuchnosti, Puchnost) * 0.5 * 180.0 / M_PI;
         Memo1->Lines->Add(" Delta FI = "  + FloatToStrF(DeltaFi, ffFixed, 20, 6));
  // ----------
       double val1 = Dobrotnost;   // --------- Добротность ---------
       double val2 = FreqMaximum;            // ---- Частота ----
       double val3 = Puchnost;            // ---- Сигнал пучности ------
       double val3_= DeltaFi;
       double val4 = FazaPuchnosti;            // ---- Фаза пучности----
       Memo1->Lines->Add("");
       Memo1->Lines->Add(FloatToStrF(val1, ffFixed, 20, 1) + "   " +
                         FloatToStrF(val2, ffFixed, 20, 4) + "   " +
                         FloatToStrF(val3, ffFixed, 20, 2) + "   " +
                         FloatToStrF(val3_, ffFixed, 20, 3) + "   " +
                         FloatToStrF(val4, ffFixed, 20, 3) + "   ");
  // ----------
}