CSmplMeasure.cs 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using OTSModelSharp.ServiceCenter;
  5. using static OTSDataType.otsdataconst;
  6. using OTSDataType;
  7. using System.Drawing;
  8. using System.Threading;
  9. using OTSCLRINTERFACE;
  10. using OTSMeasureApp._0_OTSModel.OTSDataType;
  11. using System.Windows.Forms;
  12. using System.Data;
  13. using System.IO;
  14. using OTSMeasureApp._1_OTSMeasure.Measure._3_MeasureFlow;
  15. using OpenCvSharp.Extensions;
  16. using OTSMeasureApp;
  17. using System.Diagnostics;
  18. namespace OTSModelSharp
  19. {
  20. using CHoleBSEImgsList = List<CHoleBSEImg>;
  21. public class CSmplMeasure
  22. {
  23. protected static NLog.Logger log ;
  24. protected bool bSaveThreadWorking;
  25. protected System.Threading.Thread m_thread_ptr;
  26. protected COTSSample m_Sample;
  27. protected COTSSample m_HolePreviewSample;
  28. protected CMeasure m_pMsrThread;
  29. string m_strWorkingFolder;
  30. protected CSmplMsrResult m_pSampleRstFile;
  31. CHoleBSEImgsList m_listHoleBSEImg;
  32. protected ISemController m_SemHardwareMgr;
  33. protected IScanController m_ScanHardwareMgr;
  34. protected IEDSController m_EDSController;
  35. protected Queue<COTSField> fieldQueue=new Queue<COTSField>();
  36. protected IClassifyEngine m_classifyEngine;
  37. public CSmplMeasure( string a_strWorkingFolder, COTSSample a_pSample)
  38. {
  39. m_Sample = a_pSample;
  40. log = NLog.LogManager.GetCurrentClassLogger();
  41. var expC = m_Sample.GetMsrParams().GetXRayParam().GetAnalyExpCount();
  42. var imgwidth = m_Sample.GetMsrParams().GetImageScanParam().GetImageResolutionSize().cx;
  43. var imgheight = m_Sample.GetMsrParams().GetImageScanParam().GetImageResolutionSize().cy;
  44. m_strWorkingFolder = a_strWorkingFolder;
  45. m_pSampleRstFile = new CSmplMsrResult( a_strWorkingFolder, a_pSample);
  46. m_SemHardwareMgr = SemController.GetSEMController();
  47. m_ScanHardwareMgr = ScanController.GetScanController();
  48. m_EDSController = EDSController.GetEDSController(imgwidth,imgheight,expC);
  49. m_listHoleBSEImg = new CHoleBSEImgsList();
  50. m_Sample = a_pSample;
  51. }
  52. public void SetSample(COTSSample a_pSample)
  53. {
  54. m_Sample = a_pSample;
  55. m_pSampleRstFile.SetSample(a_pSample);
  56. }
  57. public COTSSample GetSample() { return m_Sample; }
  58. public void SetHolePreviewSample(COTSSample a_pSample)
  59. {
  60. m_HolePreviewSample = a_pSample;
  61. }
  62. public COTSSample GetHolePreviewSample() { return m_HolePreviewSample; }
  63. public void SetMsrThread(CMeasure mt)
  64. {
  65. m_pMsrThread = mt;
  66. }
  67. bool SetSEMDataMrs(COTSSample sample)
  68. {
  69. var pSEMDataMsr = sample.GetSEMDataMsr();
  70. double dMag = pSEMDataMsr.GetMagnification();
  71. double dWorkDis = pSEMDataMsr.GetWorkingDistance();
  72. var pSEMCtrl = m_pMsrThread.GetSEMController();
  73. pSEMCtrl.SetMagnification(dMag);
  74. pSEMCtrl.SetWorkingDistance(dWorkDis);
  75. return true;
  76. }
  77. bool SetSEMExteralOn()
  78. {
  79. var pSEMCtrl = m_SemHardwareMgr;
  80. log.Warn("Set Scan Exteral on!");
  81. pSEMCtrl.SetScanExternal(true);
  82. return true;
  83. }
  84. // set SEM external off
  85. bool SetSEMExteralOff()
  86. {
  87. var pSEMCtrlPtr = m_SemHardwareMgr;
  88. log.Warn("Set SEM Exteral Off!");
  89. pSEMCtrlPtr.SetScanExternal(false);
  90. return true;
  91. }
  92. bool SetBSEParam()
  93. {
  94. // get scan controller
  95. var pScanController = m_ScanHardwareMgr;
  96. // scan parameters
  97. var pMsrParam = m_Sample.GetMsrParams();
  98. var pImgScanParam = pMsrParam.GetImageScanParam();
  99. // get image size
  100. var nImageSizeId = pImgScanParam.GetImageResulotion();
  101. int nResulotionId = RESOLUTION_ID_FIRST_TIE + (int)nImageSizeId;
  102. Size sizePixelImage = RESOLUTION_VALUE[nResulotionId];
  103. // get dwell time
  104. OTS_IMAGE_SCANSPEED_OPTIONS nDwellTime = pImgScanParam.GetScanImageSpeed();
  105. // convert dwell time to bruker dwell time (8, 16, 32)
  106. int nBrukerDwellTimeId;
  107. switch (nDwellTime)
  108. {
  109. case OTS_IMAGE_SCANSPEED_OPTIONS.low:
  110. nBrukerDwellTimeId = 1;
  111. break;
  112. case OTS_IMAGE_SCANSPEED_OPTIONS.meddium:
  113. nBrukerDwellTimeId = 2;
  114. break;
  115. case OTS_IMAGE_SCANSPEED_OPTIONS.high:
  116. nBrukerDwellTimeId = 3;
  117. break;
  118. default:
  119. nBrukerDwellTimeId = 1;
  120. break;
  121. }
  122. long nBrukerDwellTime = OTSDataType.otsdataconst.DWELLTIME_BRUKER_VALUES[nBrukerDwellTimeId];
  123. if (!pScanController.Init())
  124. {
  125. log.Error("SetBSEParam: failed to get scan control.");
  126. return false;
  127. }
  128. // set dwell time
  129. if (!pScanController.SetDwellTime(nBrukerDwellTime))
  130. {
  131. log.Error("SetBSEParam: failed to set dwell time (%d) for bruker system.", nBrukerDwellTime);
  132. return false;
  133. }
  134. // set image size
  135. if (!pScanController.SetImageSize(sizePixelImage.Width,sizePixelImage.Height))
  136. {
  137. // failed to set dwell time
  138. log.Error("SetBSEParam: failed to set dwell time (%d).", sizePixelImage.Height);
  139. return false;
  140. }
  141. return true;
  142. }
  143. bool SetHoleBSEParam(COTSSample sample)
  144. {
  145. // get scan controller
  146. var pScanController = m_ScanHardwareMgr;
  147. // scan parameters
  148. var pMsrParam = sample.GetMsrParams();
  149. var pImgScanParam = pMsrParam.GetImageScanParam();
  150. // get image size
  151. var nImageSizeId = pImgScanParam.GetImageResulotion();
  152. int nResulotionId = RESOLUTION_ID_FIRST_TIE + (int)nImageSizeId;
  153. Size sizePixelImage = RESOLUTION_VALUE[nResulotionId];
  154. // get dwell time
  155. OTS_IMAGE_SCANSPEED_OPTIONS nDwellTime = pImgScanParam.GetScanImageSpeed();
  156. // convert dwell time to bruker dwell time (6, 16, 32)
  157. long nBrukerDwellTime = DWELLTIME_BRUKER_VALUES[2];// choose the third option, so the dwell time will be 4 . there's no need to change here. it shoud be a const.
  158. if (!pScanController.Init())
  159. {
  160. log.Error("SetBSEParam: failed to get scan control.");
  161. return false;
  162. }
  163. // set dwell time
  164. if (!pScanController.SetDwellTime(nBrukerDwellTime))
  165. {
  166. log.Error("SetBSEParam: failed to set dwell time (%d) for bruker system.", nBrukerDwellTime);
  167. return false;
  168. }
  169. // set image size
  170. if (!pScanController.SetImageSize(sizePixelImage.Width, sizePixelImage.Height))
  171. {
  172. // failed to set dwell time
  173. log.Error("SetBSEParam: failed to set ImageSize");
  174. return false;
  175. }
  176. return true;
  177. }
  178. public void SetWorkingFolder(String a_strWorkingFolder)
  179. {
  180. // add "\\" at the string end if it is not "\\"
  181. if (a_strWorkingFolder.PadRight(1)!="\\")
  182. {
  183. a_strWorkingFolder += "\\";
  184. }
  185. m_strWorkingFolder = a_strWorkingFolder + m_Sample.GetName() + "\\";
  186. }
  187. bool CalculateUnMeasuredHoleImgCenters(COTSSample sample, out List<System.Drawing.Point> a_allpieldcenter, out List<System.Drawing.Point> a_listUnMsrFieldCenter)
  188. {
  189. // sample measure parameters
  190. CSampleParam pMsrParam = sample.GetMsrParams();
  191. COTSImgScanPrm poImageScanParam = pMsrParam.GetImageScanParam();
  192. COTSImageProcParam pImgProcParam = pMsrParam.GetImageProcessParam();
  193. CSEMDataMsr poSEMDataMsr = sample.GetSEMDataMsr();
  194. CMsrSampleStatus pStatus = sample.GetMsrStatus();
  195. // measured field centers list
  196. List<System.Drawing.PointF> listCompletedCenter = pStatus.GetCompletedFieldsCenter();
  197. // field centers list manager
  198. CFieldPositionHelper pFieldMgr = new CFieldPositionHelper();
  199. // init field centers list manager
  200. if (!pFieldMgr.Init(sample.GetMsrDomain(), poImageScanParam,0, poSEMDataMsr, listCompletedCenter))
  201. {
  202. log.Error("CalculateFieldsCenters: failed to init field centres list manager.");
  203. a_listUnMsrFieldCenter = new List<System.Drawing.Point>();
  204. a_allpieldcenter = new List<Point>();
  205. return false;
  206. }
  207. // get field centers list
  208. a_listUnMsrFieldCenter = pFieldMgr.GetUnmeasuredFieldCentrePoints();// GetFieldCentrePoints();
  209. a_allpieldcenter = pFieldMgr.GetFieldCentrePoints();
  210. // ok, return TRUE
  211. return true;
  212. }
  213. protected bool IsAborted()
  214. {
  215. return m_pMsrThread.IsMeasureStopped();
  216. }
  217. protected bool IsPaused()
  218. {
  219. var statu = m_pMsrThread.GetMsrThreadStatus();
  220. if (statu.GetStatus() == OTS_MSR_THREAD_STATUS.PAUSED)
  221. {
  222. return true;
  223. }
  224. else
  225. {
  226. return false;
  227. }
  228. }
  229. bool IsSampleOver(COTSImgScanPrm a_pScanParam)
  230. {
  231. string sStopMode = a_pScanParam.GetStopMode();
  232. int nStopField = a_pScanParam.GetStopParamFields();
  233. // completed fields number
  234. CMsrSampleStatus pMsrSampleStatus = m_Sample.GetMsrStatus();
  235. int nCompeltedField = pMsrSampleStatus.GetCompletedFields();
  236. CMsrResultItems pMsrResults = m_Sample.GetMsrResults();
  237. List<CMsrResultItem> listMsrResult = pMsrResults.GetResultItems();
  238. int nNumParticle = 0;
  239. foreach (var pResult in listMsrResult)
  240. {
  241. if (pResult.GetTypeId() > (int)OTS_PARTICLE_TYPE.NOT_IDENTIFIED)//summarize the number of the identified particle in this condition
  242. {
  243. nNumParticle += (int)pResult.GetNumber();
  244. }
  245. }
  246. TimeSpan timeSpan = pMsrSampleStatus.GetUsedTime();
  247. int nDay = timeSpan.Days;
  248. int nHour = timeSpan.Hours;
  249. int nMin = timeSpan.Minutes;
  250. int nSec = timeSpan.Seconds;
  251. int nUsedTime = nSec + nMin * 60 + nHour * 3600 + nDay * 86400;
  252. int NMeasArea = (int)pMsrResults.GetMeasuredArea();
  253. int nParticlAim = a_pScanParam.GetStopParamParticles();
  254. int nMeasTimeAim = a_pScanParam.GetStopParamMeasTime();
  255. int NMeasAreaAim = a_pScanParam.GetStopParamArea()*1000000 ;
  256. bool bRet = false;
  257. string[] str = sStopMode.Replace(" ", "").Split('+');
  258. for(int i=0;i< str.Length;i++)
  259. {
  260. switch (int.Parse(str[i].Split(':')[0])-1)
  261. {
  262. case (int)OTS_MEASURE_STOP_MODE.CoverMode:
  263. // completed fields number
  264. if (nCompeltedField == m_Sample.GetFieldsData().Count)
  265. {
  266. bRet = true;
  267. }
  268. break;
  269. case (int)OTS_MEASURE_STOP_MODE.FieldMode:
  270. if (nCompeltedField >= nStopField)
  271. {
  272. bRet = true;
  273. }
  274. break;
  275. case (int)OTS_MEASURE_STOP_MODE.ParticleMode:
  276. if (nNumParticle >= nParticlAim)
  277. {
  278. bRet = true;
  279. }
  280. break;
  281. case (int)OTS_MEASURE_STOP_MODE.TimeMode:
  282. if (nUsedTime >= nMeasTimeAim)
  283. {
  284. bRet = true;
  285. }
  286. break;
  287. case (int)OTS_MEASURE_STOP_MODE.AreaMode:
  288. if (NMeasArea >= NMeasAreaAim)
  289. {
  290. bRet = true;
  291. }
  292. break;
  293. default:
  294. break;
  295. }
  296. }
  297. return bRet;
  298. }
  299. // move SEM to the point
  300. bool MoveSEMToPoint(System.Drawing.PointF a_poi)
  301. {
  302. // get SEM controller
  303. var pSEMController = m_SemHardwareMgr;
  304. PointF a_SEMpt = new Point();
  305. CSEMStageData a_pCSEMStageData = m_pMsrThread.GetProjResultData().GetSEMStageData();
  306. int hardWareDelay = a_pCSEMStageData.GetHardWareDelay();
  307. if (!a_pCSEMStageData.ConvertOTSToSEMCoord(a_poi, ref a_SEMpt))
  308. {
  309. return false;
  310. }
  311. log.Info("Begin to move SEM stage to OTScoord:" + a_poi.X + "," + a_poi.Y);
  312. log.Info("Begin to move SEM stage to " + a_SEMpt.X + "," + a_SEMpt.Y);
  313. // move SEM to the position (rotation 0)
  314. if (!pSEMController.MoveSEMToPoint(a_SEMpt.X, a_SEMpt.Y))
  315. {
  316. log.Error("MoveSEMToPoint: failed to call MoveSEMToPoint method.");
  317. return false;
  318. }
  319. CSampleParam pMsrParam = m_Sample.GetMsrParams();
  320. if (pMsrParam.SlopParam.IsUsingSlopParam)
  321. {
  322. double wd = pMsrParam.SlopParam.GetWD(a_SEMpt);
  323. double originWd = 0;
  324. pSEMController.GetWorkingDistance(ref originWd);
  325. if ((wd - originWd) > 2)
  326. {
  327. log.Warn("Working Distance is invalid,outof the moving scope(2cm) wd=" + wd.ToString("F2"));
  328. }
  329. else
  330. {
  331. Thread.Sleep(hardWareDelay);
  332. pSEMController.SetWorkingDistance(wd);
  333. }
  334. }
  335. if (hardWareDelay > 0)
  336. {
  337. Thread.Sleep(hardWareDelay);
  338. }
  339. return true;
  340. }
  341. // Acquire a BSE image
  342. CBSEImgClr AcquireABSEImage()
  343. {
  344. // BSE image
  345. CBSEImgClr pBSEImage = null;
  346. // get scan controller
  347. var pScanController = m_ScanHardwareMgr;
  348. pBSEImage = pScanController.AcquireBSEImage();
  349. return pBSEImage;
  350. }
  351. public bool IsLowCounts(COTSParticleClr particle)
  352. {
  353. COTSXRayParam pXRayParam = m_Sample.GetMsrParams().GetXRayParam();
  354. if (pXRayParam.GetUsingXray() == true)
  355. {
  356. var thecount = particle.GetXray().GetTotalCount();
  357. var expect = pXRayParam.GetAnalyExpCount();
  358. if (thecount < expect)
  359. {
  360. particle.SetType((int)OTS_PARTICLE_TYPE.LOW_COUNT);
  361. particle.SetClassifyId((int)OTS_PARTICLE_TYPE.LOW_COUNT);
  362. particle.SetTypeColor("#000000");
  363. particle.SetTypeName("LowCounts");
  364. return true;
  365. }
  366. }
  367. return false;
  368. }
  369. public virtual void ClassifyFieldParticles(COTSField curFldData)
  370. {
  371. return;
  372. }
  373. private class SEMStateObject
  374. {
  375. private PointF pos;
  376. private double workingDistance;
  377. private CSEMDataGnr semdata;
  378. private COTSSample originalSample;
  379. private double magnification;
  380. public PointF Pos { get => pos; set => pos = value; }
  381. public double WorkingDistance { get => workingDistance; set => workingDistance = value; }
  382. public CSEMDataGnr Semdata { get => semdata; set => semdata = value; }
  383. public double Magnification { get => magnification; set => magnification = value; }
  384. public COTSSample OriginalSample { get => originalSample; set => originalSample = value; }
  385. }
  386. private class AutoResetSEMControl:IDisposable
  387. {
  388. CSmplMeasure sm;
  389. private SEMStateObject semState=null;
  390. public AutoResetSEMControl(CSmplMeasure s)
  391. {
  392. sm = s;
  393. }
  394. public SEMStateObject SemState
  395. {
  396. get => semState;
  397. set => semState = value;
  398. }
  399. public void Dispose()
  400. {
  401. if (semState != null)
  402. {
  403. sm.SetBSEParam();
  404. sm.m_SemHardwareMgr.SetMagnification(semState.Magnification);
  405. Thread.Sleep(100);
  406. sm.MoveSEMToPoint(semState.Pos);
  407. Thread.Sleep(100);
  408. sm.m_SemHardwareMgr.SetWorkingDistance(semState.WorkingDistance);
  409. }
  410. sm.SetSEMExteralOff();
  411. }
  412. }
  413. private bool GetSEMDataGnrFromHw(ref CSEMDataGnr SemDataGnr)
  414. {
  415. double kv = 0, brightness = 0, contrast = 0;
  416. var hw = SemController.GetSEMController();
  417. hw.GetSemHighTension(ref kv);
  418. hw.GetSemBrightness(ref brightness);
  419. hw.GetSemContrast(ref contrast);
  420. SemDataGnr.SetValue(kv, brightness, contrast);
  421. return true;
  422. }
  423. private void AiProcess(ref CBSEImgClr pBSEImg)
  424. {
  425. var procParam = m_Sample.GetMsrParams().GetImageProcessParam();
  426. var aiserver = procParam.GetAIServer();
  427. var originalBseData = pBSEImg.GetImageDataPtr();//获取bse 图像
  428. pBSEImg.GetWidth();
  429. int m_iWidth = pBSEImg.GetWidth();
  430. int m_iHeight = pBSEImg.GetHeight();
  431. OpenCvSharp.Mat input = new OpenCvSharp.Mat();
  432. Bitmap bitmap = CImageHandler.ToGrayBitmap(originalBseData, m_iWidth, m_iHeight);
  433. input = OpenCvSharp.Extensions.BitmapConverter.ToMat(bitmap);
  434. //OpenCvSharp.Cv2.ImShow("img", input);
  435. //OpenCvSharp.Cv2.WaitKey(0);
  436. //OpenCvSharp.Cv2.DestroyAllWindows();
  437. string baseurl = "http://" + aiserver;
  438. //test server
  439. bool test = false;
  440. if (test)
  441. {
  442. if (!AI_HttpClient.AI_Test(baseurl))
  443. {
  444. log.Info("server erro!");
  445. MessageBox.Show("server erro!");
  446. input.Dispose();
  447. return;
  448. }
  449. }
  450. if (!input.Empty())
  451. {
  452. OpenCvSharp.Mat output = new OpenCvSharp.Mat();
  453. AI_HttpClient.AI_SegformerImage_cxx(baseurl, input, ref output, 1007, 1);
  454. if (output.Empty())
  455. {
  456. log.Info("aiserver out erro!");
  457. MessageBox.Show("aiserver erro!");
  458. input.Dispose();
  459. output.Dispose();
  460. return;
  461. }
  462. output = ~output; //
  463. //将二值图复制到pBSEImg
  464. var bitData = CImageHandler.BitmapToGrayByte(output.ToBitmap());
  465. pBSEImg.SetImageData(bitData, output.Width, output.Height);
  466. //OpenCvSharp.Cv2.ImShow("out", output);
  467. //OpenCvSharp.Cv2.WaitKey(0);
  468. //OpenCvSharp.Cv2.DestroyAllWindows();
  469. input.Dispose();
  470. output.Dispose();
  471. }
  472. }
  473. public void DoMeasureForOneSample()
  474. {
  475. using (AutoResetSEMControl autoReset = new AutoResetSEMControl(this)) //when this method exit ,the SetSEMExternalOff and ResetScan will be called automatically.
  476. {
  477. // let the main thread to know that this sample measurement starts
  478. var pStatus = m_Sample.GetMsrStatus();
  479. pStatus.SetStatus(OTS_MSR_SAMPLE_STATUS.INPROCESS);
  480. // set current time to current time
  481. pStatus.ComputeTime(OTS_MSR_TIME_TYPE.START);
  482. // let main App know that the sample begin to measure
  483. ST_MSTMsg MsgSmpStart = new ST_MSTMsg(m_Sample);
  484. MsgSmpStart.InitSampleStartMsg();
  485. m_pMsrThread.SendMessageToMeasureGUI(MsgSmpStart);
  486. log.Info(m_Sample.GetName() + " Measurement started!");
  487. // get SEM controller to set magnification and working distance
  488. if (!SetSEMDataMrs(m_Sample))
  489. {
  490. log.Error("DoMeasure: fail to set SEM data.");
  491. pStatus.SetStatus(OTS_MSR_SAMPLE_STATUS.FAILED);
  492. pStatus.ComputeTime(OTS_MSR_TIME_TYPE.STOPPED);
  493. return;
  494. }
  495. // set the BSE scan param
  496. if (!SetBSEParam())
  497. {
  498. log.Error("DoMeasure: fail to set BSE param.");
  499. pStatus.SetStatus(OTS_MSR_SAMPLE_STATUS.FAILED);
  500. pStatus.ComputeTime(OTS_MSR_TIME_TYPE.STOPPED);
  501. return;
  502. }
  503. var pSEMDataGnr = new CSEMDataGnr();
  504. log.Info("Get Kv, Brightness and Contrast!");
  505. GetSEMDataGnrFromHw(ref pSEMDataGnr);
  506. m_pSampleRstFile.SetSEMGnr(pSEMDataGnr);
  507. // record SEM data
  508. COTSMsrPrjResultData pProjMgrFile = m_pMsrThread.GetProjResultData();
  509. CSEMStageData pSEMStageData = pProjMgrFile.GetSEMStageData();
  510. m_pSampleRstFile.SetSEMStageData(pSEMStageData);
  511. // record stage
  512. CStage pStage = pProjMgrFile.GetStage();
  513. m_pSampleRstFile.SetSEMStage(pStage);
  514. //-----save the static measure result file data into xml file and the dynamic data of every field will be saved into sqlite database
  515. log.Info("Create result file!");
  516. if (!m_pSampleRstFile.CreateResultFiles())
  517. {// failed to call measure result file Save method
  518. log.Error("DoMeasure: failed to call measure result file Save method.");
  519. pStatus.SetStatus(OTS_MSR_SAMPLE_STATUS.FAILED);
  520. pStatus.ComputeTime(OTS_MSR_TIME_TYPE.STOPPED);
  521. return;
  522. }
  523. //------
  524. var FldDatas = m_Sample.GetFieldsData();
  525. for (int i = 0; i < FldDatas.Count; ++i)
  526. {// check and break if stop button is clicked
  527. var curFld = FldDatas[i];
  528. if (curFld.GetIsMeasureComplete())
  529. {
  530. continue;
  531. }
  532. if (IsPaused())
  533. {// measure stopped
  534. pStatus.SetStatus(OTS_MSR_SAMPLE_STATUS.PAUSED);
  535. // record end time
  536. pStatus.ComputeTime(OTS_MSR_TIME_TYPE.STOPPED);
  537. //must wait for the saving data thread finished,or we'll get null pointer exception when we stop the measure process.
  538. while (fieldQueue.Count() > 0)
  539. {
  540. Thread.Sleep(100);
  541. }
  542. SetSEMExteralOff();
  543. // update thread measure status class, let the main thread know that this sample measurement stopped
  544. ST_MSTMsg MsgSmpStop = new ST_MSTMsg(m_Sample);
  545. MsgSmpStop.InitSamplePausedMsg();
  546. m_pMsrThread.SendMessageToMeasureGUI(MsgSmpStop);
  547. while (IsPaused())
  548. {
  549. Thread.Sleep(300);
  550. }
  551. }
  552. if (IsAborted())
  553. {// measure stopped
  554. pStatus.SetStatus(OTS_MSR_SAMPLE_STATUS.STOPPED);
  555. // record end time
  556. pStatus.ComputeTime(OTS_MSR_TIME_TYPE.STOPPED);
  557. //must wait for the saving data thread finished,or we'll get null pointer exception when we stop the measure process.
  558. while (fieldQueue.Count() > 0)
  559. {
  560. Thread.Sleep(100);
  561. }
  562. break;
  563. }
  564. // check if sample measurement completes
  565. COTSImgScanPrm pScanParam = m_Sample.GetMsrParams().GetImageScanParam();
  566. if (IsSampleOver(pScanParam))
  567. {
  568. pStatus.SetStatus(OTS_MSR_SAMPLE_STATUS.SUCCESSED);
  569. pStatus.ComputeTime(OTS_MSR_TIME_TYPE.COMPLT);
  570. break;
  571. }
  572. // get a field center
  573. System.Drawing.PointF poiFieldCentre = curFld.GetOTSPosition();
  574. // update thread measure status class, let the main thread know that starts a new field
  575. ST_MSTMsg MsgFieldStart = new ST_MSTMsg(m_Sample,curFld);
  576. MsgFieldStart.InitFieldStartMsg();
  577. m_pMsrThread.SendMessageToMeasureGUI(MsgFieldStart);
  578. int fldNo = curFld.GetId();
  579. log.Warn("Current field:" + fldNo.ToString());
  580. // move SEM to the field center
  581. if (!MoveSEMToPoint(poiFieldCentre))
  582. {// failed to move SEM to the position
  583. log.Error("DoMeasure: failed to move SEM to the field centre point.");
  584. pStatus.SetStatus(OTS_MSR_SAMPLE_STATUS.FAILED);
  585. // record end time
  586. pStatus.ComputeTime(OTS_MSR_TIME_TYPE.STOPPED);
  587. return;
  588. }
  589. log.Info("Begin to Acquire BSE image!");
  590. // take BSE image for the fields
  591. CBSEImgClr pBSEImg = AcquireABSEImage();
  592. // let the main thread to know that image process is completed
  593. if (pBSEImg == null)
  594. {
  595. log.Error("ImageProcess: can't get no background image.");
  596. pStatus.SetStatus(OTS_MSR_SAMPLE_STATUS.FAILED);
  597. return;
  598. }
  599. //ai 提取二值图
  600. AiProcess(ref pBSEImg);
  601. curFld.SetBSEImage(pBSEImg);
  602. //BSEData
  603. ST_MSTMsg MsgFieldBSE = new ST_MSTMsg(m_Sample,curFld);
  604. MsgFieldBSE.InitFieldBSEImageMsg();
  605. m_pMsrThread.SendMessageToMeasureGUI(MsgFieldBSE);
  606. log.Info("Acquire BSE image success! Processing image...");
  607. // image process
  608. FieldImageProcess(curFld);
  609. COTSXRayParam pXRayParam = m_Sample.GetMsrParams().GetXRayParam();
  610. if (pXRayParam.GetUsingXray() == true)
  611. {
  612. foreach (var p in curFld.GetListAnalysisParticles())
  613. {
  614. p.SetIsXrayParticle(true);
  615. }
  616. CollectParticlesXrayData(curFld);
  617. }
  618. m_Sample.GetMsrStatus().SetStatus(OTS_MSR_SAMPLE_STATUS.SUCCESSED);
  619. curFld.SetIsMeasureComplete(true);
  620. log.Info("Begin to classify particles! particle num:" + curFld.GetListAnalysisParticles().Count);
  621. ClassifyFieldParticles(curFld);
  622. //start db save
  623. StartSaveFileThread(ref curFld);
  624. SendFieldParticlesInfoToGUI(curFld, m_Sample.GetMsrStatus());
  625. }
  626. while (bSaveThreadWorking)//wait untill all the field data has been saved.
  627. {
  628. Thread.Sleep(1000);
  629. log.Warn("db saving!");
  630. }
  631. TheLastWorkOfSampleMeasure();
  632. }
  633. }
  634. public void TheLastWorkOfSampleMeasure()
  635. {
  636. COTSSample theSample = m_Sample;
  637. var pStatus = theSample.GetMsrStatus();
  638. pStatus.ComputeTime(OTS_MSR_TIME_TYPE.COMPLT);
  639. pStatus.SetStatus(OTS_MSR_SAMPLE_STATUS.SUCCESSED);
  640. // let main thread to know that this sample measurement completes
  641. ST_MSTMsg MsgSmplEnd = new ST_MSTMsg(m_Sample);
  642. MsgSmplEnd.InitSampleCompleteMsg();
  643. m_pMsrThread.SendMessageToMeasureGUI(MsgSmplEnd);
  644. string userdB = m_Sample.GetMsrParams().GetSTDName();
  645. if(userdB.ToLower() != "nostddb" && userdB.ToLower() != "nostddb.db")
  646. {
  647. try
  648. {
  649. string userdBpath= System.Windows.Forms.Application.StartupPath + "\\Config\\SysData\\" + m_Sample.GetMsrParams().GetSTDName() + ".db";
  650. File.Copy(userdBpath, m_pSampleRstFile.GetFieldFileSubFolderStr().Remove(m_pSampleRstFile.GetFieldFileSubFolderStr().IndexOf("FIELD_FILES")) + m_Sample.GetMsrParams().GetSTDName() + ".db", true);
  651. }
  652. catch(Exception ex)
  653. {
  654. MessageBox.Show("userdB copy failed:" + ex.ToString());
  655. }
  656. }
  657. }
  658. public bool DoMEasureForReMeasure()
  659. {
  660. return true;
  661. }
  662. public virtual void FieldImageProcess(COTSField curFldData)
  663. {
  664. PointF fldCenter = curFldData.GetOTSPosition();
  665. CSEMStageData a_pCSEMStageData = m_pMsrThread.GetProjResultData().GetSEMStageData();
  666. PointF semPos = new Point();
  667. a_pCSEMStageData.ConvertOTSToSEMCoord(fldCenter, ref semPos);
  668. curFldData.SetSemPos(semPos);
  669. //first step:remove background of the bse image and compound all the finded particles.
  670. log.Info("Begin to process image and get all particles!");
  671. GetOriginalParticles(ref curFldData);
  672. log.Info("Begin to filter particles!");
  673. FilterParticles(ref curFldData);//filter according to the xraylimit
  674. log.Info("Begin to Calculate the image property of every particle!");
  675. var analysisparts = curFldData.GetListAnalysisParticles();
  676. curFldData.CalParticleImageProp(analysisparts);//calculate particle image property such as feret diameter, DMAX etc.
  677. SelectParticles(ref curFldData);
  678. CSampleParam pMsrParam = m_Sample.GetMsrParams();
  679. COTSImageProcParam pImgProcessParam = pMsrParam.GetImageProcessParam();
  680. var overlap = pImgProcessParam.GetOverlapParam();
  681. if (overlap > 0)
  682. {
  683. curFldData.RemoveDuplicateOverlapParticles(overlap);
  684. }
  685. CalculateParticleAbsolutPos(ref curFldData);
  686. curFldData.InitParticles(pImgProcessParam);
  687. return ;
  688. }
  689. private void FilterParticles(ref COTSField curFldData)
  690. {
  691. log.Info("filter particle according to xraylimit");
  692. var listXray = curFldData.GetAllParticles().OrderByDescending(x => x.GetActualArea()).ToList();
  693. var listXray1 = new List<COTSParticleClr>();
  694. var pXRayParam =m_Sample.GetMsrParams().GetXRayParam();
  695. if (listXray.Count > pXRayParam.GetXrayLimit())
  696. {
  697. for (var i = 0; i < pXRayParam.GetXrayLimit(); i++)
  698. {
  699. listXray1.Add(listXray[i]);
  700. }
  701. }
  702. else
  703. {
  704. listXray1 = listXray;
  705. }
  706. curFldData.SetListAnalysisParticles(listXray1);
  707. log.Info("Analysis particles:" + listXray1.Count);
  708. }
  709. private void SelectParticles(ref COTSField curFldData)
  710. {
  711. var selconditiondic = m_Sample.GetMsrParams().GetImageProcessParam().GetParticleSelConditionDic();
  712. var listselparts = new List<COTSParticleClr>();
  713. var excludeparts= new List<COTSParticleClr>();
  714. if (selconditiondic.ContainsKey("dmax"))
  715. {
  716. log.Info("Select particles according to dmax");
  717. var rng = selconditiondic["dmax"];
  718. foreach (var p in curFldData.GetListAnalysisParticles())
  719. {
  720. if (p.GetDMAX() < rng.GetStart() || p.GetDMAX() >= rng.GetEnd())
  721. {
  722. excludeparts.Add(p);
  723. }
  724. else
  725. {
  726. log.Info("dmax=" + p.GetDMAX().ToString("F2"));
  727. }
  728. }
  729. }
  730. if (selconditiondic.ContainsKey("dmin"))
  731. {
  732. log.Info("Select particles according to dmin");
  733. var rng = selconditiondic["dmin"];
  734. foreach (var p in curFldData.GetListAnalysisParticles())
  735. {
  736. if (p.GetDMIN() < rng.GetStart() || p.GetDMIN() >= rng.GetEnd())
  737. {
  738. if (!excludeparts.Contains(p))
  739. {
  740. excludeparts.Add(p);
  741. }
  742. else
  743. {
  744. log.Info("dmin=" + p.GetDMIN().ToString("F2"));
  745. }
  746. }
  747. }
  748. }
  749. if (selconditiondic.ContainsKey("orientation"))
  750. {
  751. log.Info("Select particles according to orientation");
  752. var rng = selconditiondic["orientation"];
  753. foreach (var p in curFldData.GetListAnalysisParticles())
  754. {
  755. if (p.GetORIENTATION() < rng.GetStart() || p.GetORIENTATION() >= rng.GetEnd())
  756. {
  757. if (!excludeparts.Contains(p))
  758. {
  759. excludeparts.Add(p);
  760. }
  761. else
  762. {
  763. log.Info("orientation=" + p.GetORIENTATION().ToString("F2"));
  764. }
  765. }
  766. }
  767. }
  768. if (selconditiondic.ContainsKey("aspect"))
  769. {
  770. log.Info("Select particles according to aspect");
  771. var rng = selconditiondic["aspect"];
  772. foreach (var p in curFldData.GetListAnalysisParticles())
  773. {
  774. double aspect = p.GetDMAX() / p.GetDMIN();
  775. if (aspect < rng.GetStart() || aspect >= rng.GetEnd())
  776. {
  777. if (!excludeparts.Contains(p))
  778. {
  779. excludeparts.Add(p);
  780. }
  781. else
  782. {
  783. log.Info("aspect=" + aspect.ToString("F2"));
  784. }
  785. }
  786. }
  787. }
  788. foreach (var p in curFldData.GetListAnalysisParticles())
  789. {
  790. if (!excludeparts.Contains(p))
  791. {
  792. listselparts.Add(p);
  793. }
  794. }
  795. curFldData.SetListAnalysisParticles(listselparts);
  796. log.Info("Analysis particles:" + listselparts.Count);
  797. }
  798. public void GetOriginalParticles(ref COTSField curFldData)
  799. {
  800. // get image process parameter
  801. CSampleParam pMsrParam = m_Sample.GetMsrParams();
  802. COTSImageProcParam pImgProcessParam = pMsrParam.GetImageProcessParam();
  803. var specialPartsparam = pMsrParam.GetSpecialGrayRangeParam();
  804. var pixelsize = m_Sample.CalculatePixelSize();
  805. if (specialPartsparam != null && specialPartsparam.GetIsToRun())
  806. {
  807. List<CSpecialGrayRange> ranges = pMsrParam.GetSpecialGrayRangeParam().GetSpecialGreyRanges();
  808. foreach (var grayRange in ranges)
  809. {
  810. CIntRangeClr range = new CIntRangeClr(grayRange.range.GetStart(), grayRange.range.GetEnd());
  811. CDoubleRangeClr diaRange = new CDoubleRangeClr(grayRange.diameterRange.GetStart(), grayRange.diameterRange.GetEnd());
  812. curFldData.GetPartsBySpecialGray(range, diaRange, pixelsize, grayRange.ifCollectXray);
  813. }
  814. }
  815. var ifCollectxray = pMsrParam.GetXRayParam().GetUsingXray();
  816. // remove BES image background
  817. curFldData.RemoveImgBGAndGetParticles(pImgProcessParam, pixelsize, ifCollectxray);
  818. log.Info("Find all particle num:" +curFldData.GetAllParticles().Count);
  819. return;
  820. }
  821. public virtual void CollectParticlesXrayData(COTSField curFldData)
  822. {
  823. var allParts = curFldData.GetListXrayParticles();
  824. var smallparts = new List<COTSParticleClr>();
  825. var bigparts = new List<COTSParticleClr>();
  826. double quantifyThreshold = m_Sample.GetMsrParams().GetXRayParam().GetFeatureModeMinSize();
  827. foreach (var part in allParts)
  828. {
  829. double equalCircleDiameter = Math.Sqrt(part.GetActualArea() / 3.14159) * 2f;
  830. if (equalCircleDiameter < quantifyThreshold)
  831. {
  832. smallparts.Add(part);
  833. }
  834. else
  835. {
  836. bigparts.Add(part);
  837. }
  838. }
  839. log.Info("SmallQuantifyParts (<" + quantifyThreshold.ToString("f2") + "): " + smallparts.Count);
  840. log.Info("BigQuantifyParts (>=" + quantifyThreshold.ToString("f2") + "): " + bigparts.Count);
  841. curFldData.CreateXrayList(smallparts);
  842. curFldData.CreateXrayList(bigparts);
  843. // get x-ray parameters
  844. COTSXRayParam pXRayParam = m_Sample.GetMsrParams().GetXRayParam();
  845. var workmode = pXRayParam.GetScanMode();
  846. if (workmode == OTS_X_RAY_SCAN_MODE.PointMode)
  847. {
  848. uint nXRayAQTime;
  849. if (bigparts.Count > 0)
  850. {
  851. nXRayAQTime = (uint)pXRayParam.GetMidAnalyAQTime();
  852. log.Info("Begin to collect xraydata:" + bigparts.Count +"(" +nXRayAQTime.ToString()+") on " + workmode.ToString());
  853. m_EDSController.GetXRayByParts(bigparts, nXRayAQTime, true);
  854. }
  855. if (smallparts.Count > 0)
  856. {
  857. Thread.Sleep(500);//add delay here,or else the eds system will halt.
  858. nXRayAQTime = (uint)pXRayParam.GetSmallPartXrayTime();
  859. log.Info("Begin to collect xraydata:" + smallparts.Count + "(" + nXRayAQTime.ToString() + ") on " + workmode.ToString());
  860. m_EDSController.GetXRayByParts(smallparts, nXRayAQTime, true);
  861. }
  862. }
  863. else if (workmode == OTS_X_RAY_SCAN_MODE.FeatureMode)
  864. {
  865. uint nXRayAQTime;
  866. if (bigparts.Count > 0)
  867. {
  868. log.Info("Begin to collect xraydata:" + bigparts.Count + " on " + OTS_X_RAY_SCAN_MODE.FeatureMode.ToString());
  869. nXRayAQTime = (uint)pXRayParam.GetMidAnalyAQTime();
  870. m_EDSController.GetXRayByFeatures(bigparts, nXRayAQTime, true);
  871. }
  872. if (smallparts.Count > 0)
  873. {
  874. Thread.Sleep(500);
  875. log.Info("Begin to collect xraydata:" + smallparts.Count + " on " + OTS_X_RAY_SCAN_MODE.PointMode.ToString());
  876. nXRayAQTime = (uint)pXRayParam.GetSmallPartXrayTime();
  877. m_EDSController.GetXRayByParts(smallparts, nXRayAQTime, true);
  878. }
  879. }
  880. return;
  881. }
  882. public virtual void QuantifyParticlesXrayData(COTSField curFldData)
  883. {
  884. var parts = curFldData.GetListXrayParticles();
  885. foreach (var p in parts)
  886. {
  887. m_EDSController.QuantifyXrayByPart(p);
  888. }
  889. }
  890. public void DoHolePreview()
  891. {
  892. using (AutoResetSEMControl autoReset = new AutoResetSEMControl(this))
  893. {
  894. //----------memorize the state of sem
  895. var semstate = new SEMStateObject();
  896. double dMagnification = m_Sample.GetSEMDataMsr().GetMagnification();
  897. double wd = m_Sample.GetSEMDataMsr().GetWorkingDistance();
  898. ISemController sem = m_SemHardwareMgr;
  899. double posX=0, posY=0,posR=0;
  900. sem.GetSemPositionXY(ref posX, ref posY, ref posR);
  901. CSEMStageData a_pCSEMStageData = m_pMsrThread.GetProjResultData().GetSEMStageData();
  902. Point pos = new Point((int)posX, (int)posY);
  903. PointF otsPos = new Point(0, 0);
  904. if (!a_pCSEMStageData.ConvertSEMToOTSCoord(pos, ref otsPos))
  905. {
  906. return;
  907. }
  908. semstate.Pos = otsPos;
  909. semstate.Magnification = dMagnification;
  910. semstate.WorkingDistance = wd;
  911. autoReset.SemState = semstate;
  912. //-------------------------------------
  913. // let the main thread to know that this sample measurement starts
  914. CMsrSampleStatus pStatus = m_HolePreviewSample.GetMsrStatus();
  915. pStatus.SetStatus(OTS_MSR_SAMPLE_STATUS.INPROCESS);
  916. // set current time to current time
  917. pStatus.ComputeTime(OTS_MSR_TIME_TYPE.START);
  918. // get SEM controller to set magnification and working distance
  919. if (!SetSEMDataMrs(m_HolePreviewSample))
  920. {
  921. log.Error("DoHolePreview: fail to set SEM data.");
  922. pStatus.SetStatus(OTS_MSR_SAMPLE_STATUS.FAILED);
  923. // record end time
  924. pStatus.ComputeTime(OTS_MSR_TIME_TYPE.STOPPED);
  925. return;
  926. }
  927. // set the BSE scan param
  928. if (!SetHoleBSEParam(m_HolePreviewSample))
  929. {
  930. log.Error("DoHolePreview: fail to set BSE param.");
  931. pStatus.SetStatus(OTS_MSR_SAMPLE_STATUS.FAILED);
  932. // record end time
  933. pStatus.ComputeTime(OTS_MSR_TIME_TYPE.STOPPED);
  934. return;
  935. }
  936. // calculate field centers
  937. List<System.Drawing.Point> listFieldCenter;
  938. List<System.Drawing.Point> alllistFieldCenter ;
  939. if (!CalculateUnMeasuredHoleImgCenters(m_HolePreviewSample, out alllistFieldCenter,out listFieldCenter))
  940. {// failed to calculate field centers
  941. log.Error("DoHolePreview: failed to calculate field centers.");
  942. pStatus.SetStatus(OTS_MSR_SAMPLE_STATUS.FAILED);
  943. // record end time
  944. pStatus.ComputeTime(OTS_MSR_TIME_TYPE.STOPPED);
  945. return;
  946. }
  947. // go through each field
  948. //int nNewFieldId = 0;
  949. for ( int i = 0; i < listFieldCenter.Count; ++i)
  950. {// check and break if stop button is clicked
  951. if (IsAborted())
  952. {// measure stopped
  953. log.Trace("DoHolePreview: measure thread is stopped.");
  954. pStatus.SetStatus(OTS_MSR_SAMPLE_STATUS.STOPPED);
  955. // record end time
  956. pStatus.ComputeTime(OTS_MSR_TIME_TYPE.STOPPED);
  957. return;
  958. }
  959. // check if sample measurement completes
  960. COTSImgScanPrm pScanParam = m_Sample.GetMsrParams().GetImageScanParam();
  961. int nTotalFieldSize = listFieldCenter.Count;
  962. // get a field center
  963. System.Drawing.Point poiFieldCentre = listFieldCenter[i];
  964. // move SEM to the field center
  965. if (!MoveSEMToPoint(poiFieldCentre))
  966. {// failed to move SEM to the position
  967. log.Error("DoHolePreview: failed to move SEM to the field centre point.");
  968. pStatus.SetStatus(OTS_MSR_SAMPLE_STATUS.FAILED);
  969. // record end time
  970. pStatus.ComputeTime(OTS_MSR_TIME_TYPE.STOPPED);
  971. return;
  972. }
  973. // take BSE image for the fields
  974. CBSEImgClr pBSEIamge = AcquireABSEImage();
  975. if (pBSEIamge==null)
  976. {
  977. // failed to acquire a BSE image
  978. log.Error("DoHolePreview: failed to acquire a BSE image.");
  979. pStatus.SetStatus(OTS_MSR_SAMPLE_STATUS.FAILED);
  980. // record end time
  981. pStatus.ComputeTime(OTS_MSR_TIME_TYPE.STOPPED);
  982. return;
  983. }
  984. //BSEData
  985. ST_MSTMsg MsgFieldBSE=new ST_MSTMsg(m_HolePreviewSample);
  986. MsgFieldBSE.InitHolePreBSEDataMsg(pBSEIamge,poiFieldCentre);
  987. m_pMsrThread.SendHolePreviewMessageToMeasureGUI(MsgFieldBSE);
  988. if (pStatus.GetStatus() != OTS_MSR_SAMPLE_STATUS.INPROCESS)
  989. {
  990. // measurement failed or stopped
  991. log.Error("DoHolePreview: measurement failed or stopped.");
  992. pStatus.SetStatus(OTS_MSR_SAMPLE_STATUS.FAILED);
  993. // record end time
  994. pStatus.ComputeTime(OTS_MSR_TIME_TYPE.STOPPED);
  995. return;
  996. }
  997. //save the result to project file
  998. Rectangle oImageRect = (Rectangle)pBSEIamge.GetImageRect();
  999. CHoleBSEImg pHoleBSEImg =new CHoleBSEImg(oImageRect,poiFieldCentre);
  1000. pHoleBSEImg.SetImageData( pBSEIamge.GetImageDataPtr(),oImageRect.Width,oImageRect.Height);
  1001. m_listHoleBSEImg.Add(pHoleBSEImg);
  1002. }
  1003. pStatus.ComputeTime(OTS_MSR_TIME_TYPE.STOPPED);
  1004. //calculate measure time
  1005. pStatus.SetStatus(OTS_MSR_SAMPLE_STATUS.SUCCESSED);
  1006. // let main thread to know that this sample measurement completes
  1007. ST_MSTMsg MsgSmplEnd=new ST_MSTMsg(m_HolePreviewSample);
  1008. MsgSmplEnd.InitHolePreSampleEndMsg();
  1009. m_pMsrThread.SendHolePreviewMessageToMeasureGUI(MsgSmplEnd);
  1010. }
  1011. }
  1012. // Cumulate field data info
  1013. public virtual bool CumulateFieldData( List<COTSParticleClr> listParticles, double a_nMeasuredArea)
  1014. {
  1015. // get measure result items of the sample
  1016. CMsrResultItems pMsrResults = m_Sample.GetMsrResults();
  1017. // cumulate field data info
  1018. pMsrResults.CumulateMeasuredArea(a_nMeasuredArea);
  1019. // cumulate ratio
  1020. double dRatio = 10000 * pMsrResults.GetTotalParticleArea();
  1021. dRatio = dRatio / pMsrResults.GetMeasuredArea();
  1022. pMsrResults.SetRatio(dRatio);
  1023. // go through the particles list
  1024. foreach (COTSParticleClr pParticle in listParticles)
  1025. {
  1026. // create a measure result item
  1027. pMsrResults.CumulateMeasureResult(pParticle);
  1028. }
  1029. m_Sample.SetMsrResults(pMsrResults);
  1030. return true;
  1031. }
  1032. public bool SaveFieldData(COTSField fldData, string filedFileFoler)
  1033. {
  1034. string strFieldFileFolder = filedFileFoler;
  1035. CBSEImageFileMgr pBSEImgFileMgr = new CBSEImageFileMgr();
  1036. pBSEImgFileMgr.SetBSEImg(fldData.GetBSEImage());
  1037. int nId = fldData.GetId();
  1038. string sFieldId;
  1039. sFieldId = nId.ToString();
  1040. string strBSEFilePathname = strFieldFileFolder + "\\" + m_pSampleRstFile.SMPL_MSR_RESULT_FIELDS_BSE + sFieldId + pBSEImgFileMgr.BMP_IMG_FILE_EXT;
  1041. if (!pBSEImgFileMgr.SaveIntoBitmap(strBSEFilePathname))
  1042. {
  1043. log.Error("SaveFieldFiles: save BSE file failed.");
  1044. return false;
  1045. }
  1046. // IncA Data list
  1047. CIncAFileMgr pDBFileMgr = m_pSampleRstFile.DBFileMgr;
  1048. pDBFileMgr.SaveStatusDataToDB();
  1049. var fldDB = pDBFileMgr.GetFieldDB();
  1050. log.Warn("Start saving particle data.");
  1051. var fldcmd = fldDB.GetSavingAFieldcmdObj(fldData.GetId(), fldData.GetOTSPosition(), fldData.GetSemPos());
  1052. List<KeyValuePair<string, System.Data.SQLite.SQLiteParameter[]>> fldcmds = new List<KeyValuePair<string, System.Data.SQLite.SQLiteParameter[]>>();
  1053. fldcmds.Add(fldcmd);
  1054. pDBFileMgr.ExecuteNonQueryBatch(ref fldcmds);
  1055. //remomove the invalid particles
  1056. var cmds = pDBFileMgr.GetSavingParticleDataToDBCmds(fldData.GetListAnalysisParticles(), fldData.GetOTSPosition());
  1057. pDBFileMgr.ExecuteNonQueryBatch(ref cmds);
  1058. CPosXrayDBMgr PosXrayDBMgr = pDBFileMgr.GetPosXrayDBMgr();
  1059. var listAnalysisPosXray = new List<CPosXrayClr>();
  1060. foreach (var p in fldData.GetListXrayParticles())
  1061. {
  1062. listAnalysisPosXray.Add(p.GetXray());
  1063. }
  1064. var cmds1 = PosXrayDBMgr.GetSavingXrayCmds(listAnalysisPosXray, true);
  1065. pDBFileMgr.ExecuteNonQueryBatch(ref cmds1);
  1066. return true;
  1067. }
  1068. protected void SaveFieldMgrData()
  1069. {
  1070. while (bSaveThreadWorking)
  1071. {
  1072. while (fieldQueue.Count() > 0)
  1073. {
  1074. COTSField f = fieldQueue.Dequeue();
  1075. //save to disk first ,then pop . if the size is 0,then we know all the saving work is done.
  1076. log.Info("Begin to save particles data! particle num:" + f.GetListAnalysisParticles().Count);
  1077. SaveFieldData(f, m_pSampleRstFile.GetFieldFileSubFolderStr());
  1078. }
  1079. if (fieldQueue.Count() == 0)
  1080. {
  1081. bSaveThreadWorking = false; //must set this flag,so the main thread can know this thread has exited.
  1082. log.Warn("finished batch saving");
  1083. return;
  1084. }
  1085. }
  1086. return;
  1087. }
  1088. private void SendFieldParticlesInfoToGUI(COTSField curFld,CMsrSampleStatus pStatus)
  1089. {
  1090. double measuredArea = 0; // this area should be the field area
  1091. var a_pBSEImg = curFld.GetBSEImage();
  1092. double dPixelSize = curFld.GetPixelSize();
  1093. measuredArea = a_pBSEImg.GetHeight() * a_pBSEImg.GetWidth() * dPixelSize * dPixelSize; //Get measured area
  1094. CumulateFieldData(curFld.GetListAnalysisParticles(), measuredArea);
  1095. log.Info("Send field data to screen!");
  1096. pStatus.AddCompletedFieldCenter(curFld.GetOTSPosition());
  1097. //Field Data
  1098. // record end time
  1099. pStatus.ComputeTime(OTS_MSR_TIME_TYPE.STOPPED);
  1100. ST_MSTMsg MsgFieldEnd = new ST_MSTMsg(m_Sample,curFld);
  1101. MsgFieldEnd.InitFieldDataMsg();
  1102. m_pMsrThread.SendMessageToMeasureGUI(MsgFieldEnd);
  1103. }
  1104. protected void StartSaveFileThread(ref COTSField a_pFieldMgr)
  1105. {
  1106. fieldQueue.Enqueue(a_pFieldMgr);
  1107. if (fieldQueue.Count() > 0) //if there's data in the queue and the previous thread has finished then start a new thread.
  1108. {
  1109. if (bSaveThreadWorking == false)
  1110. {
  1111. bSaveThreadWorking = true;
  1112. m_thread_ptr = new System.Threading.Thread(this.SaveFieldMgrData);//m_thread_ptr = shared_ptr<thread>(new thread(&CSmplMeasureInc::SaveFieldMgrData, this));
  1113. m_thread_ptr.IsBackground = true;
  1114. m_thread_ptr.Start();
  1115. }
  1116. }
  1117. }
  1118. public void ParticleSpecialTreatment(ref COTSField fld)
  1119. {
  1120. //we adopt such a strategy here:if some particles satisfy the predefined condition then we go through the second collecting with max EDS time,so that we got a more acurate result.
  1121. Dictionary<COTSParticleClr, int> mapPartXray = new Dictionary<COTSParticleClr, int>();
  1122. double edsTime = 0; //to store the EDSTime returned from the engine.
  1123. var bigparts = fld.GetListXrayParticles();
  1124. var m_ClassifyEngine = new CClassifyEngine();
  1125. for (int i = 0; i < bigparts.Count(); i++)
  1126. {
  1127. var engine = m_ClassifyEngine.GetExpressionClassifyEngine(m_Sample.GetMsrParams().GetSTDName());
  1128. var p = bigparts[i];
  1129. // there will be very less particle satisfied the condition ,so we use only one MaxEDS time,though we set MaxEDSTime for every rule separately .Here we store the last one.
  1130. //if the particle satisfied the MaxEDS condition then we go through the second colleting.Here we record the particle and the EDSTime and the corresponding xray position.
  1131. edsTime = engine.IfNeedMaxEDS(p);
  1132. if (edsTime > 0)
  1133. {
  1134. mapPartXray[p] = i;
  1135. }
  1136. }
  1137. List<COTSParticleClr> partsMax = new List<COTSParticleClr>();
  1138. if (mapPartXray.Count() > 0)
  1139. {
  1140. foreach (var p in mapPartXray)
  1141. {
  1142. partsMax.Add(p.Key);
  1143. }
  1144. List<CPosXrayClr> maxEDSXrays = new List<CPosXrayClr>();
  1145. m_EDSController.GetXRayByFeatures(partsMax, edsTime, true);
  1146. }
  1147. }
  1148. public void CalculateParticleAbsolutPos(ref COTSField curFldData)
  1149. {
  1150. double dPixelSize = m_Sample.CalculatePixelSize();
  1151. CSEMStageData pCSEMStageData = m_pMsrThread.GetProjResultData().GetSEMStageData();
  1152. foreach (var p in curFldData.GetListAnalysisParticles())
  1153. {
  1154. //Point fldOtsPos = new Point((curFldData.OTSPos.X, curFldData.OTSPos.Y);
  1155. PointF semP = new PointF(); ;
  1156. Point semPos = new Point();
  1157. pCSEMStageData.ConvertOTSToSEMCoord(curFldData.GetOTSPosition(), ref semP);
  1158. semPos.X = (int)semP.X;
  1159. semPos.Y = (int)semP.Y;
  1160. p.SetSEMPos(semPos);
  1161. }
  1162. }
  1163. }
  1164. }