Графики распределений
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 | 'Начало описания 'Данный скрипт рисует графики вероятностных распределений: нормального, биномиального, хи-квадрат; 'Пользователь задаёт число степеней свободы и т.д. Типы графиков и подписи могут 'быть дополнительно настроены из диалогового окна. Скрипт кое-как контролирует вводимые значения '(знаки и пределы вводимых значений), но пока здесь не реализована проверка против запросов графиков 'с числом категорий, большим, чем SPSS может отобразить: 3000. ' 'Создан 27.09.1998, автор Rolf Kjшller (rolf.kjoeller@get2net.dk) . 'Конец описания Option Explicit 'Для локализованных версий Windows, использующих запятую (,) 'вместо точки (.) в качестве десятичного разделителя, 'измените значение в следующей строке с False на True Const DECIMAL_COMMA As Boolean = False Global strMacrocall As String Global booInputIsOK As Boolean Global strMainTitle As String Global strSubTitle As String Global intChartType As Integer Sub Main Dim blnOverwriteWarning As Boolean If SPSSVersion8 Then 'не даём предупреждения в версиях, выше 7.5, если 'текущий файл данных не был изменён со времени последнего сохранения blnOverwriteWarning = objSpssApp.Documents.GetDataDoc(0).Modified Else 'в ранних версиях можно проинсталлировать код query.sbs чтобы проверять это blnOverwriteWarning = True End If If blnOverwriteWarning Then If vbCancel = MsgBox ("Текущий файл данных будет заменён! Продолжить?", _ vbExclamation + vbOkCancel) Then Exit Sub End If End If Call MainDialog End Sub Sub MainDialog Dim distributions$(3) distributions$(1)="Нормальное" distributions$(2)="Биномиальное" distributions$(3)="Хи-квадрат" Dim stepvalues$(6) stepvalues$(1)="1" stepvalues$(2)="0.5" stepvalues$(3)="0.1" stepvalues$(4)="0.05" stepvalues$(5)="0.01" stepvalues$(6)="0.005" Begin Dialog UserDialog 420,140,"Графики вероятностных распределений",.RunMainDialog Text 30,7,220,21,"Распределение:",.maintext OKButton 290,20,100,20,.cmdOK CancelButton 290,50,100,20,.cmdCancel DropListBox 30,20,225,77,distributions(),.distribution Text 30,50,140,21,"Среднее:",.meantext TextBox 210,50,45,20,.mean Text 30,75,140,20,"Стд. отклонение:",.stdevtext TextBox 210,75,45,20,.stdev Text 30,100,140,21,"Шаг вычисления:",.stepvaluetext ListBox 185,100,70,28,stepvalues(),.stepvalue Text 30,50,140,21,"Число попыток n:",.ntext TextBox 210,50,45,20,.n Text 30,75,140,20,"Вероятность успеха:",.Probtext TextBox 210,75,45,20,.Prob Text 30,50,140,20,"Число ст. свободы:",.dfstext TextBox 210,50,45,20,.dfs PushButton 290,100,100,20,"Настройки ...",.cmdOptions End Dialog Dim MainDlg As UserDialog Dialog MainDlg End Sub Sub OptionsDialog Begin Dialog UserDialog 480,140,"Графики вероятностных распределений: Настройки",.RunOptionsDialog Text 30,7,140,20,"Заголовки:",.Title PushButton 290,20,100,20,"Продолжить",.cmdContinue TextBox 30,20,230,20,.MainTitle TextBox 30,50,230,20,.Subtitle OptionGroup.ChartType OptionButton 30,100,120,20,"Линейный",.OptionButton1 OptionButton 160,100,120,20,"С областями",.OptionButton2 OptionButton 290,100,120,20,"Столбиковый",.OptionButton3 Text 30,87,90,14,"График:",.Text1 End Dialog Dim OptionsDlg As UserDialog Dialog OptionsDlg End Sub Private Function RunMainDialog(DlgItem As String, Action As Integer, SuppValue As Integer) As Boolean Select Case Action Case 1 'Инициализация диалогового окна DlgVisible "meantext",True DlgVisible "mean",True DlgVisible "stdevtext",True DlgVisible "stdev",True DlgVisible "stepvaluetext",True DlgVisible "stepvalue",True DlgVisible "dfstext",False DlgVisible "dfs",False DlgVisible "ntext",False DlgVisible "n",False DlgVisible "Probtext",False DlgVisible "Prob",False DlgValue "stepvalue",2 DlgFocus "distribution" strMainTitle="Нормальное расрпеделение" strSubTitle="Среднее=" + DlgText("mean") + ", стд. отклонение=" + DlgText("stdev") intChartType=0 Case 2 'Изменение значения или нажатие кнопки Select Case DlgItem Case "distribution" Select Case SuppValue Case 0 DlgVisible "meantext",True DlgVisible "mean",True DlgVisible "stdevtext",True DlgVisible "stdev",True DlgVisible "ntext",False DlgVisible "n",False DlgVisible "Probtext",False DlgVisible "Prob",False DlgVisible "dfstext",False DlgVisible "dfs",False DlgVisible "stepvaluetext",True DlgVisible "stepvalue",True strMainTitle="Нормальное распределение" strSubTitle="Среднее=" + DlgText("mean") + ", стд. отклонение=" + DlgText("stdev") intChartType=0 Case 1 DlgVisible "meantext",False DlgVisible "mean",False DlgVisible "stdevtext",False DlgVisible "stdev",False DlgVisible "ntext",True DlgVisible "n",True DlgVisible "Probtext",True DlgVisible "Prob",True DlgVisible "dfstext",False DlgVisible "dfs",False DlgVisible "stepvaluetext",False DlgVisible "stepvalue",False strMainTitle="Биномиальное распределение" strSubTitle="n=" + DlgText("n") + ", вероятность=" + DlgText("Prob") intChartType=2 Case 2 DlgVisible "meantext",False DlgVisible "mean",False DlgVisible "stdevtext",False DlgVisible "stdev",False DlgVisible "ntext",False DlgVisible "n",False DlgVisible "Probtext",False DlgVisible "Prob",False DlgVisible "dfstext",True DlgVisible "dfs",True DlgVisible "stepvaluetext",True DlgVisible "stepvalue",True strMainTitle="Распределение хи-квадрат" strSubTitle="df=" + DlgText("dfs") intChartType=0 End Select Case "cmdOK" strMainTitle="'" + strMainTitle + "'" strSubTitle="'" + strSubTitle + "'" Select Case DlgText("distribution") Case "Нормальное" Call CheckInput (DlgText("mean"), DlgText("stdev")) If booInputIsOK Then Call BuildMacroCall (DlgText("mean"), DlgText("stdev")) Call plot RunMainDialog = False Else RunMainDialog = True End If Case "Биномиальное" Call CheckInput (DlgText("n"), DlgText("Prob")) If booInputIsOK Then Call BuildMacroCall (DlgText("n"), DlgText("Prob")) Call plot RunMainDialog = False Else RunMainDialog = True End If Case "Хи-квадрат" Call CheckInput (DlgText("dfs")) If booInputIsOK Then Call BuildMacroCall (DlgText("dfs")) Call plot RunMainDialog = False Else RunMainDialog = True End If End Select Case "cmdCancel" End Case "cmdOptions" Call OptionsDialog RunMainDialog = True End Select Case 3 'Изменено значение в текстовых полях или списке Select Case DlgItem Case "mean" strMainTitle="Нормальное распределение" strSubTitle="Среднее=" + DlgText("mean") + ", стд. отклонение=" + DlgText("stdev") intChartType=0 Case "stdev" strMainTitle="Нормальное распределение" strSubTitle="Среднее=" + DlgText("mean") + ", стд. отклонение=" + DlgText("stdev") intChartType=0 Case "n" strMainTitle="Биномиальное распределение" strSubTitle="n=" + DlgText("n") + ", вероятность=" + DlgText("Prob") intChartType=2 Case "Prob" strMainTitle="Биномиальное распределение" strSubTitle="n=" + DlgText("n") + ", вероятность=" + DlgText("Prob") intChartType=2 Case "dfs" strMainTitle="Распределение хи-квадрат" strSubTitle="df=" + DlgText("dfs") intChartType=0 End Select Case 4 'Изменение фокуса Case 5 'Зарезервировано End Select End Function Private Function RunOptionsDialog(DlgItem As String, Action As Integer, SuppValue As Integer) As Boolean Select Case Action Case 1 'Инициализация диалогового окна DlgText "MainTitle", strMainTitle DlgText "SubTitle", strSubTitle DlgValue "ChartType", intChartType Case 2 'Изменено значение или нажата кнопка Select Case DlgItem Case "cmdContinue" strMainTitle=DlgText("MainTitle") strSubTitle=DlgText("SubTitle") intChartType=DlgValue("ChartType") Exit Function End Select Case 3 'Изменено значение текстового поля или списка Case 4 'Изменение фокуса Case 5 'Зарезервировано End Select End Function Sub CheckInput (ParamArray InputValueList()) Dim i As Integer Dim j As Integer booInputIsOK=False For j=0 To UBound(InputValueList) '*************************************** 'Первая проверка: является ли введённое значение числом? '*************************************** If DECIMAL_COMMA Then 'точки заменяются на запятые: For i=1 To Len(InputValueList(j)) If Mid(InputValueList(j),i,1) = "." Then InputValueList(j)=Left(InputValueList(j),i-1)+","+Right(InputValueList(j),Len(InputValueList(j))-i) Next i End If booInputIsOK=IsNumeric(InputValueList(j)) If Not booInputIsOK Then MsgBox "Поле ввода пусто, либо содержит нечисловые или множественные значения" Exit Sub End If '**************************************************** 'Вторая проверка: укладывается ли введённое значение в допустимый интервал? '**************************************************** Select Case DlgText("distribution") Case "Нормальное" If j=1 Then booInputIsOK = (CDbl(InputValueList(j))>0) If Not booInputIsOK Then MsgBox "Стандартное отклонение должно быть больше 0" Exit Sub End If End If Case "Биномиальное" Select Case j Case 0 booInputIsOK = (CDbl(InputValueList(j))>0 And CDbl(InputValueList(j))=Int(CDbl(InputValueList(j)))) If Not booInputIsOK Then MsgBox "n должно быть больше 0" Exit Sub End If Case 1 booInputIsOK = (CDbl(InputValueList(j))>=0 And CDbl(InputValueList(j))<=1) If Not booInputIsOK Then MsgBox "Вероятность должна находится в интервале от 0 до 1" Exit Sub End If End Select Case "Хи-квадрат" booInputIsOK = (CDbl(InputValueList(j))>0 And CDbl(InputValueList(j))=Int(CDbl(InputValueList(j)))) If Not booInputIsOK Then MsgBox "Число степеней свободы должно быть положительным целым числом" Exit Sub End If End Select Next j End Sub Sub BuildMacroCall(ParamArray InputValueList()) Dim i As Integer Dim j As Integer For j=0 To UBound(InputValueList) 'запятые заменяются точками: For i=1 To Len(InputValueList(j)) If Mid(InputValueList(j),i,1) = "," Then InputValueList(j)=Left(InputValueList(j),i-1)+"."+Right(InputValueList(j),Len(InputValueList(j))-i) Next i Next j Select Case DlgText("distribution") Case "Нормальное" strMacrocall="!norm mean=" + InputValueList(0) + " stdev=" + InputValueList(1) + " step=" + DlgText("stepvalue") + " ." Case "Биномиальное" strMacrocall="!bin n=" + InputValueList(0) + " p=" + InputValueList(1) + " ." Case "Хи-квадрат" strMacrocall="!chisq df=" + InputValueList(0) + " step=" + DlgText("stepvalue") + " ." End Select End Sub Sub plot Dim strCommand As String strCommand = strCommand + "SET ERRORS=OFF ." &vbCrLf strCommand = strCommand + "/******************************************************************************" &vbCrLf strCommand = strCommand + "/* Нормальное:" &vbCrLf strCommand = strCommand + "/******************************************************************************" &vbCrLf strCommand = strCommand + "DEFINE !norm (mean=!TOKENS(1) /stdev=!TOKENS(1) /step=!DEFAULT(0.05) !TOKENS(1)) ." &vbCrLf strCommand = strCommand + "NEW FILE ." &vbCrLf strCommand = strCommand + "INPUT PROGRAM ." &vbCrLf strCommand = strCommand + "LOOP x=(-4*!stdev+!mean) TO (4*!stdev+!mean) BY !step ." &vbCrLf strCommand = strCommand + "COMPUTE cpx=CDF.NORM(x,!mean,!stdev) ." &vbCrLf strCommand = strCommand + "COMPUTE px=CDF.NORM(x,!mean,!stdev)-CDF.NORM(LAG(x),!mean,!stdev) ." &vbCrLf strCommand = strCommand + "IF x EQ (-4*!stdev+!mean) px=cpx ." &vbCrLf strCommand = strCommand + "END CASE ." &vbCrLf strCommand = strCommand + "END LOOP ." &vbCrLf strCommand = strCommand + "END FILE ." &vbCrLf strCommand = strCommand + "END INPUT PROGRAM ." &vbCrLf strCommand = strCommand + "EXECUTE ." &vbCrLf strCommand = strCommand + "VARIABLE LABELS x 'Z' px 'p(z=Z)' cpx 'p(z<=Z)' ." &vbCrLf strCommand = strCommand + "!ENDDEFINE ." &vbCrLf strCommand = strCommand + "/******************************************************************************" &vbCrLf strCommand = strCommand + "/* Биномиальное:" &vbCrLf strCommand = strCommand + "/******************************************************************************" &vbCrLf strCommand = strCommand + "DEFINE !bin (n=!TOKENS(1) /p=!TOKENS(1)) ." &vbCrLf strCommand = strCommand + "NEW FILE ." &vbCrLf strCommand = strCommand + "INPUT PROGRAM ." &vbCrLf strCommand = strCommand + "LOOP x=0 TO !n BY 1 ." &vbCrLf strCommand = strCommand + "COMPUTE cpx=CDF.BINOM(x,!n,!p) ." &vbCrLf strCommand = strCommand + "COMPUTE px=CDF.BINOM(x,!n,!p)-CDF.BINOM(LAG(x),!n,!p) ." &vbCrLf strCommand = strCommand + "IF x EQ 0 px=cpx ." &vbCrLf strCommand = strCommand + "END CASE ." &vbCrLf strCommand = strCommand + "END LOOP ." &vbCrLf strCommand = strCommand + "END FILE ." &vbCrLf strCommand = strCommand + "END INPUT PROGRAM ." &vbCrLf strCommand = strCommand + "EXECUTE ." &vbCrLf strCommand = strCommand + "FORMAT x (F4) ." &vbCrLf strCommand = strCommand + "VARIABLE LABELS x 'X' px 'p(x=X)' cpx 'p(x<=X)' ." &vbCrLf strCommand = strCommand + "!ENDDEFINE ." &vbCrLf strCommand = strCommand + "/******************************************************************************" &vbCrLf strCommand = strCommand + "/* Хи-квадрат:" &vbCrLf strCommand = strCommand + "/******************************************************************************" &vbCrLf strCommand = strCommand + "DEFINE !chisq (df=!TOKENS(1) /step=!TOKENS(1)) ." &vbCrLf strCommand = strCommand + "NEW FILE ." &vbCrLf strCommand = strCommand + "INPUT PROGRAM ." &vbCrLf strCommand = strCommand + "LOOP x=0 TO 5*!df BY !step ." &vbCrLf strCommand = strCommand + "COMPUTE cpx=CDF.CHISQ(x,!df) ." &vbCrLf strCommand = strCommand + "COMPUTE px=CDF.CHISQ(x,!df)-CDF.CHISQ(LAG(x),!df) ." &vbCrLf strCommand = strCommand + "IF x EQ 0 px=cpx ." &vbCrLf strCommand = strCommand + "DO IF cpx GT 0.9999 ." &vbCrLf strCommand = strCommand + "BREAK ." &vbCrLf strCommand = strCommand + "END IF ." &vbCrLf strCommand = strCommand + "END CASE ." &vbCrLf strCommand = strCommand + "END LOOP ." &vbCrLf strCommand = strCommand + "END FILE ." &vbCrLf strCommand = strCommand + "END INPUT PROGRAM ." &vbCrLf strCommand = strCommand + "EXECUTE ." &vbCrLf strCommand = strCommand + "VARIABLE LABELS x 'Q' cpx 'p(q<=Q)' px 'p(q=Q)' ." &vbCrLf strCommand = strCommand + "!ENDDEFINE ." &vbCrLf strCommand = strCommand + "/******************************************************************************" &vbCrLf strCommand = strCommand + "/* Plot:" &vbCrLf strCommand = strCommand + "/******************************************************************************" &vbCrLf strCommand = strCommand + "DEFINE !plot (type=!TOKENS(1)) ." &vbCrLf strCommand = strCommand + "!IF (!type !EQ 0) !THEN ." &vbCrLf strCommand = strCommand + "GRAPH" &vbCrLf strCommand = strCommand + "/TITLE=" + strMainTitle &vbCrLf strCommand = strCommand + "/SUBTITLE=" + strSubTitle &vbCrLf strCommand = strCommand + "/LINE(SIMPLE)=VALUE(cpx) BY x ." &vbCrLf strCommand = strCommand + "GRAPH" &vbCrLf strCommand = strCommand + "/TITLE=" + strMainTitle &vbCrLf strCommand = strCommand + "/SUBTITLE=" + strSubTitle &vbCrLf strCommand = strCommand + "/LINE(SIMPLE)=VALUE(px) BY x ." &vbCrLf strCommand = strCommand + "!IFEND ." &vbCrLf strCommand = strCommand + "!IF (!type !EQ 1) !THEN ." &vbCrLf strCommand = strCommand + "GRAPH" &vbCrLf strCommand = strCommand + "/TITLE=" + strMainTitle &vbCrLf strCommand = strCommand + "/SUBTITLE=" + strSubTitle &vbCrLf strCommand = strCommand + "/LINE(AREA)=VALUE(cpx) BY x ." &vbCrLf strCommand = strCommand + "GRAPH" &vbCrLf strCommand = strCommand + "/TITLE=" + strMainTitle &vbCrLf strCommand = strCommand + "/SUBTITLE=" + strSubTitle &vbCrLf strCommand = strCommand + "/LINE(AREA)=VALUE(px) BY x ." &vbCrLf strCommand = strCommand + "!IFEND ." &vbCrLf strCommand = strCommand + "!IF (!type !EQ 2) !THEN ." &vbCrLf strCommand = strCommand + "GRAPH" &vbCrLf strCommand = strCommand + "/TITLE=" + strMainTitle &vbCrLf strCommand = strCommand + "/SUBTITLE=" + strSubTitle &vbCrLf strCommand = strCommand + "/BAR(SIMPLE)=VALUE(cpx) BY x ." &vbCrLf strCommand = strCommand + "GRAPH" &vbCrLf strCommand = strCommand + "/TITLE=" + strMainTitle &vbCrLf strCommand = strCommand + "/SUBTITLE=" + strSubTitle &vbCrLf strCommand = strCommand + "/BAR(SIMPLE)=VALUE(px) BY x ." &vbCrLf strCommand = strCommand + "!IFEND ." &vbCrLf strCommand = strCommand + "!ENDDEFINE ." &vbCrLf strCommand = strCommand + "SET ERRORS=LISTING ." &vbCrLf strCommand = strCommand + "/******************************************************************************" &vbCrLf strCommand = strCommand + strMacrocall &vbCrLf strCommand = strCommand + "!plot type=" + Str(intChartType) &vbCrLf objSpssApp.ExecuteCommands strCommand , False End Sub Function SPSSVersion8 As Boolean 'включаем обработчик ошибок On Error Resume Next 'это вызовет ошибку в SPSS 7.5, в частности: ' Error 10091 ' OLE Automation: no such property or method. objSpssApp.ScriptParameter(0) SPSSVersion8 = (Err = 0) 'обнуляем объект ошибки, если что-то там есть Err.Clear 'выключаем обработчик ошибок On Error GoTo 0 End Function |
Related pages
...
Navigate from here