def test_saveload_modelresult_exception(): """Make sure the proper exceptions are raised when needed.""" model, _pars = create_model_params(x, y) save_model(model, SAVE_MODEL) with pytest.raises(AttributeError, match=r'needs saved ModelResult'): load_modelresult(SAVE_MODEL) clear_savefile(SAVE_MODEL)
def test_save_load_modelresult(dill): """Save/load ModelResult with/without dill.""" if dill: pytest.importorskip("dill") else: lmfit.jsonutils.HAS_DILL = False # create model, perform fit, save ModelResult and perform some tests model, params = create_model_params(x, y) result = model.fit(y, params, x=x) save_modelresult(result, SAVE_MODELRESULT) file_exists = wait_for_file(SAVE_MODELRESULT, timeout=10) assert file_exists text = '' with open(SAVE_MODELRESULT, 'r') as fh: text = fh.read() assert_between(len(text), 8000, 25000) # load the saved ModelResult from file and compare results result_saved = load_modelresult(SAVE_MODELRESULT) check_fit_results(result_saved) clear_savefile(SAVE_MODEL)
def load_modelresult(self, inpfile): """read a customized ModelResult""" result = load_modelresult(inpfile) for prefix in list(self.fit_components.keys()): self.onDeleteComponent(self, prefix=prefix) for comp in result.model.components: isbkg = comp.prefix in result.user_options['bkg_components'] self.addModel(model=comp.func.__name__, prefix=comp.prefix, isbkg=isbkg) for comp in result.model.components: parwids = self.fit_components[comp.prefix].parwids for pname, par in result.params.items(): if pname in parwids: wids = parwids[pname] if wids.minval is not None: wids.minval.SetValue(par.min) if wids.maxval is not None: wids.maxval.SetValue(par.max) val = result.init_values.get(pname, par.value) wids.value.SetValue(val) self.fill_form(result.user_options) return result
def onLoadFitResult(self, event=None): dlg = wx.FileDialog(self, message="Load Saved File Model", wildcard=ModelWcards, style=wx.FD_OPEN) rfile = None if dlg.ShowModal() == wx.ID_OK: rfile = dlg.GetPath() dlg.Destroy() if rfile is None: return self.larch_eval("# peakmodel = lm_load_modelresult('%s')" %rfile) result = load_modelresult(str(rfile)) for prefix in list(self.fit_components.keys()): self.onDeleteComponent(self, prefix=prefix) for comp in result.model.components: isbkg = comp.prefix in result.user_options['bkg_components'] self.addModel(model=comp.func.__name__, prefix=comp.prefix, isbkg=isbkg) for comp in result.model.components: parwids = self.fit_components[comp.prefix].parwids for pname, par in result.params.items(): if pname in parwids: wids = parwids[pname] if wids.minval is not None: wids.minval.SetValue(par.min) if wids.maxval is not None: wids.maxval.SetValue(par.max) val = result.init_values.get(pname, par.value) wids.value.SetValue(val) self.fill_form(result.user_options)
def test_saveload_modelresult_expression_model(): """Test for ModelResult.loads()/dumps() for ExpressionModel. * make sure that the loaded ModelResult has `init_params` and `init_fit`. """ savefile = 'expr_modres.txt' x = np.linspace(-10, 10, 201) amp, cen, wid = 3.4, 1.8, 0.5 y = amp * np.exp(-(x - cen)**2 / (2 * wid**2)) / (np.sqrt(2 * np.pi) * wid) y = y + np.random.normal(size=x.size, scale=0.01) gmod = ExpressionModel( "amp * exp(-(x-cen)**2 /(2*wid**2))/(sqrt(2*pi)*wid)") result = gmod.fit(y, x=x, amp=5, cen=5, wid=1) save_modelresult(result, savefile) time.sleep(0.25) result2 = load_modelresult(savefile) assert result2 is not None assert result2.init_fit is not None assert_allclose((result2.init_fit - result.init_fit).sum() + 1.00, 1.00, rtol=1.0e-2) os.unlink(savefile)
def test_saveload_usersyms(): """Test save/load of modelresult with non-trivial user symbols, this example uses a VoigtModel, wheree `wofz()` is used in a constraint expression""" x = np.linspace(0, 20, 501) y = gaussian(x, 1.1, 8.5, 2) + lorentzian(x, 1.7, 8.5, 1.5) np.random.seed(20) y = y + np.random.normal(size=len(x), scale=0.025) model = VoigtModel() pars = model.guess(y, x=x) result = model.fit(y, pars, x=x) savefile = 'tmpvoigt_modelresult.sav' save_modelresult(result, savefile) assert_param_between(result.params['sigma'], 0.7, 2.1) assert_param_between(result.params['center'], 8.4, 8.6) assert_param_between(result.params['height'], 0.2, 1.0) time.sleep(0.25) result2 = load_modelresult(savefile) assert_param_between(result2.params['sigma'], 0.7, 2.1) assert_param_between(result2.params['center'], 8.4, 8.6) assert_param_between(result2.params['height'], 0.2, 1.0)
def SaveFitParams(self): """ Save the Results of the fit in a .zip file using numpy.savez(). """ fitresult = load_modelresult(self.label + '/modelresult_' + self.label + '.sav') fitparams = fitresult.params c, stdc, x0, stdx0, height, stdheight, sigma, stdsigma, gamma, stdgamma, fwhm, stdfwhm = ( [] for i in range(12)) for name in list(fitparams.keys()): par = fitparams[name] param = ufloat(par.value, par.stderr) if ('c' in name): param = param * self.maxyvalue c.append(param.n) stdc.append(param.s) elif ('height' in name): param = param * self.maxyvalue height.append(param.n) stdheight.append(param.s) elif ('x0' in name): x0.append(param.n) stdx0.append(param.s) elif ('sigma' in name): sigma.append(param.n) stdsigma.append(param.s) elif ('gamma' in name): gamma.append(param.n) stdgamma.append(param.s) elif ('fwhm' in name): fwhm.append(param.n) stdfwhm.append(param.s) np.savez(self.label + '/fitparams_' + self.label, x0=x0, stdx0=stdx0, c=c, stdc=c, height=height, stdheight=stdheight, sigma=sigma, stdsigma=stdsigma, gamma=gamma, stdgamma=stdgamma, fwhm=fwhm, stdfwhm=stdfwhm)
def test_savelod_modelresult_items(): clear_savefile(SAVE_MODELRESULT) x, y = XDAT, YDAT model, params = create_model_params(x, y) result = model.fit(y, params, x=x) save_modelresult(result, SAVE_MODELRESULT) time.sleep(0.25) file_exists = wait_for_file(SAVE_MODELRESULT, timeout=10) assert(file_exists) time.sleep(0.25) loaded = load_modelresult(SAVE_MODELRESULT) assert(len(result.data) == len(loaded.data)) assert(abs(max(result.data) - max(loaded.data)) < 0.001) for pname in result.params.keys(): assert( abs(result.init_params[pname].value - loaded.init_params[pname].value) < 0.001)
def test_saveload_modelresult_attributes(): """Test for restoring all attributes of the ModelResult.""" model, params = create_model_params(x, y) result = model.fit(y, params, x=x) save_modelresult(result, SAVE_MODELRESULT) time.sleep(0.25) file_exists = wait_for_file(SAVE_MODELRESULT, timeout=10) assert file_exists time.sleep(0.25) loaded = load_modelresult(SAVE_MODELRESULT) assert len(result.data) == len(loaded.data) assert_allclose(result.data, loaded.data) for pname in result.params.keys(): assert_allclose(result.init_params[pname].value, loaded.init_params[pname].value) clear_savefile(SAVE_MODELRESULT)
def plotSingleBin(self, cfg_par, binID, doFit=False): key = 'general' workDir = cfg_par[key]['workdir'] cubeDir = cfg_par[key]['cubeDir'] #open datacube f = fits.open(cfg_par[key]['dataCubeName']) dd = f[0].data f.close() #open datacube if cfg_par['gFit']['method'] != 'pixel': f = fits.open(cfg_par[key]['outVorNoise']) nn = f[0].data f.close() lineInfo = tP.openLineList(cfg_par) #open table for bins wave, xAxis, yAxis, pxSize, noiseBin, vorBinInfo, dataSpec = tP.openVorLineOutput( cfg_par, cfg_par['general']['outVorLineTableName'], cfg_par['general']['outVorSpectra']) hdul = fits.open(cfg_par['general']['outVorLineTableName']) tabGen = hdul[1].data lambdaMin = np.log(cfg_par['gFit']['lambdaMin']) lambdaMax = np.log(cfg_par['gFit']['lambdaMax']) idxMin = int( np.where(abs(wave - lambdaMin) == abs(wave - lambdaMin).min())[0]) idxMax = int( np.where(abs(wave - lambdaMax) == abs(wave - lambdaMax).min())[0]) idxTable = int(np.where(tabGen['BIN_ID'] == int(binID))[0][0]) y = dd[idxMin:idxMax, int(tabGen['PixY'][idxTable]), int(tabGen['PixX'][idxTable])] all_zeros = not np.any(y) waveCut = wave[idxMin:idxMax] if doFit == False and os.path.exists(cfg_par[key]['modNameDir'] + str(binID) + '_' + cfg_par['gFit']['modName'] + '.sav'): result = load_modelresult(cfg_par[key]['modNameDir'] + str(binID) + '_' + cfg_par['gFit']['modName'] + '.sav') elif doFit == True: print('''\t+---------+\n\t ...fitting...\n\t+---------+''') gMod, gPars = self.lineModDef(cfg_par, waveCut, y, lineInfo) all_zeros = not np.any(y) if all_zeros != True: result = gMod.fit(y, gPars, x=waveCut) vals = result.params.valuesdict() save_modelresult( result, cfg_par['general']['modNameDir'] + str(binID) + '_' + cfg_par['gFit']['modName'] + '.sav') else: print('''\t+---------+\n\t spectrum is empty\n\t+---------+''') print('''\t+---------+\n\t EXIT with ERROR\n\t+---------+''') sys.exit(0) cfg_par['gPlot']['loadModel'] = True if cfg_par['gFit']['method'] != 'pixel': noiseVec = nn[idxMin:idxMax, int(tabGen['PixY'][idxTable]), int(tabGen['PixX'][idxTable])] else: noiseVec = np.zeros(len(waveCut)) #noiseVec[idxMin:idxMax] -= np.nanmedian(noiseVec[idxMin:idxMax]) #print(np.nanmean(noiseVec[idxMin:idxMax]),noiseVec[idxMin:idxMax]) #print(np.nanmean(y),y) #plot Fit #self.plotSpecFit(waveCut, y,result,noiseVec[idxMin:idxMax],i,j,tab,vorBinInfo[index]) print('''\t+---------+\n\t ...plotting...\n\t+---------+''') sP.plotLineZoom(cfg_par, waveCut, y, result, noiseVec, int(tabGen['PixX'][idxTable]), int(tabGen['PixY'][idxTable]), lineInfo, tabGen[:][idxTable]) print('''\t+---------+\n\t bin Plotted\n\t+---------+''') return 0
#!/usr/bin/env python # <examples/doc_model_loadmodelresult2.py> import matplotlib.pyplot as plt import numpy as np from lmfit.model import load_modelresult dat = np.loadtxt('NIST_Gauss2.dat') x = dat[:, 1] y = dat[:, 0] result = load_modelresult('nistgauss_modelresult.sav') print(result.fit_report()) plt.plot(x, y, 'bo') plt.plot(x, result.best_fit, 'r-') plt.show() # <end examples/doc_model_loadmodelresult2.py>
# <examples/doc_model_loadmodelresult.py> import matplotlib.pyplot as plt import numpy as np from lmfit.model import load_modelresult data = np.loadtxt('model1d_gauss.dat') x = data[:, 0] y = data[:, 1] result = load_modelresult('gauss_modelresult.sav') print(result.fit_report()) plt.plot(x, y, 'bo') plt.plot(x, result.best_fit, 'r-') plt.show() # <end examples/doc_model_loadmodelresult.py>
def do_load_modelresult(): result = load_modelresult(SAVE_MODELRESULT) check_fit_results(result)
def gPlot(self, cfg_par): key = 'general' workDir = cfg_par[key]['workdir'] #open line lineList lineInfo = tP.openLineList(cfg_par) diffusion = 1e-5 #open table for bins wave, xAxis, yAxis, pxSize, noiseBin, vorBinInfo = tP.openTablesPPXF( cfg_par, workDir + cfg_par[key]['outVorTableName'], workDir + cfg_par[key]['tableSpecName']) #open datacube f = fits.open(cfg_par[key]['cubeDir'] + cfg_par[key]['dataCubeName']) hh = f[0].header dd = f[0].data modNameDir = cfg_par[key]['modNameDir'] #define x-axis array lambdaMin = np.log(cfg_par['gFit']['lambdaMin']) lambdaMax = np.log(cfg_par['gFit']['lambdaMax']) idxMin = int( np.where(abs(wave - lambdaMin) == abs(wave - lambdaMin).min())[0]) idxMax = int( np.where(abs(wave - lambdaMax) == abs(wave - lambdaMax).min())[0]) Ydim = dd.shape[1] Xdim = dd.shape[2] binID, binArr, fitResArr, lineArr = tP.makeInputArrays( cfg_par, lineInfo, Xdim, Ydim) counter = 0 #for j in range(205,208): # for i in range(250,252): for j in range(0, dd.shape[1]): for i in range(0, dd.shape[2]): y = dd[idxMin:idxMax, j, i] waveCut = wave[idxMin:idxMax] #check if spectrum is not empty if np.sum(y) > 0: # identify voronoi bin xVal = xAxis[i] yVal = yAxis[j] index = np.where( (vorBinInfo['X'] < (xVal + pxSize / 2. + diffusion)) & ((xVal - pxSize / 2. - diffusion) < vorBinInfo['X']) & (vorBinInfo['Y'] < (yVal + pxSize / 2. + diffusion)) & ((yVal - pxSize / 2. - diffusion) < vorBinInfo['Y'])) if np.sum(index) > 0: binArr = tP.updateBinArray(cfg_par, binArr, vorBinInfo, index, i, j, counter) binIDName = binArr['BIN_ID'][counter] else: fitResArr = np.delete(fitResArr, counter, 0) lineArr = np.delete(lineArr, counter, 0) counter += 1 continue #check if it is first time in bin if binIDName not in binID[:, :] and np.sum(index) > 0: binID[j, i] = binIDName noiseVec = noiseBin[binIDName][:] noiseVec[idxMin:idxMax] -= np.nanmean( noiseVec[idxMin:idxMax]) # FIT result = load_modelresult(cfg_par[key]['modNameDir'] + str(binIDName) + '_' + cfg_par['gFit']['modName'] + '.sav') cfg_par['gPlot']['loadModel'] = True #plot Fit if cfg_par['gPlot']['enable'] == True: #self.plotSpecFit(waveCut, y,result,noiseVec[idxMin:idxMax],i,j,lineInfo,vorBinInfo[index]) sP.plotLineZoom(cfg_par, waveCut, y, result, noiseVec[idxMin:idxMax], i, j, lineInfo, vorBinInfo[index]) counter += 1 f.close() print('''\t+---------+\n\t gPlot done\n\t+---------+''') return 0
def widthCentroid(cfg_par, lines, wave, lineInfo, dLambda, sigmaCen, counter, binID, tabGen, residuals): #tt=Table([lines['BIN_ID']]) modName = cfg_par['gFit']['modName'] result = load_modelresult(cfg_par['general']['modNameDir'] + str(binID) + '_' + cfg_par['gFit']['modName'] + '.sav') comps = result.eval_components() for ii in range(0, len(lineInfo['ID'])): lambdaRest = lineInfo['Wave'][ii] waveInRed = cfg_par['general']['redshift'] * lambdaRest + lambdaRest indexWaveInRed = int( np.where( abs(np.exp(wave) - waveInRed) == abs(np.exp(wave) - waveInRed).min())[0]) dLIn = dLambda[indexWaveInRed] dLIn1 = np.log(waveInRed + dLIn / 2.) - np.log(waveInRed - dLIn / 2.) dLIn1kms = cvP.lambdaVRad(waveInRed + dLIn / 2., lambdaRest) - np.float( cfg_par['general']['velsys']) lineName = str(lineInfo['Name'][ii]) + str(int(lineInfo['Wave'][ii])) if '[' in lineName: lineName = lineName.replace("[", "") lineName = lineName.replace("]", "") lineNameID = lineName lineThresh = float(lineInfo['SNThresh'][ii]) if modName == 'g1': lineFit = comps['g1ln' + str(ii) + '_'] amp = result.params['g1ln' + str(ii) + '_amplitude'] if modName == 'g2': lineFit = comps['g1ln' + str(ii) + '_'] + comps['g2ln' + str(ii) + '_'] amp = result.params['g1ln' + str(ii) + '_amplitude'] + result.params['g2ln' + str(ii) + '_amplitude'] elif modName == 'g3': lineFit = comps['g1ln' + str(ii) + '_'] + comps['g2ln' + str(ii) + '_'] + comps['g3ln' + str(ii) + '_'] amp = result.params['g1ln' + str(ii) + '_amplitude'] + result.params[ 'g2ln' + str(ii) + '_amplitude'] + result.params['g3ln' + str(ii) + '_amplitude'] centreFit = result.params['g1ln' + str(ii) + '_center'] index = np.where(tabGen['BIN_ID'] == binID)[0] indexCentroid = np.where(lines['BIN_ID'] == binID)[0] thresHold = residuals['SN_NII6583'][indexCentroid] sigmaThresh = lines['g1_sigIntr_NII6583'][indexCentroid] if amp != 0: tck = interpolate.splrep(wave[:-1], lineFit, s=0) waveNew = np.linspace(np.min(wave), np.max(wave), 1e5) lineFit = interpolate.splev(waveNew, tck, der=0) waveVel = cvP.lambdaVRad(np.exp(waveNew), lineInfo['Wave'][ii]) #centroid if modName == 'g2': centroidG1 = lines['g1_Centre_' + str(lineNameID)][indexCentroid] centroidG2 = lines['g2_Centre_' + str(lineNameID)][indexCentroid] ampG1 = lines['g1_Amp_' + str(lineNameID)][indexCentroid] ampG2 = lines['g2_Amp_' + str(lineNameID)][indexCentroid] centroidG1Lambda = cvP.vRadLambda(centroidG1, lambdaRest) centroidG2Lambda = cvP.vRadLambda(centroidG2, lambdaRest) centroidToT = np.divide( np.sum([ np.multiply(centroidG1Lambda, ampG1) + np.multiply(centroidG2Lambda, ampG2) ]), np.sum([ampG1, ampG2])) centroidToT = cvP.lambdaVRad(centroidToT, lambdaRest) sigmaCen['centroid_' + lineName][indexCentroid] = centroidToT elif modName == 'g1': centroidToT = lines['g1_Centre_' + str(lineNameID)][indexCentroid] sigmaCen['centroid_' + lineName][indexCentroid] = centroidToT sigmaCen['logCentroid_' + lineName][indexCentroid] = np.log10( np.abs(sigmaCen['centroid_' + lineName][indexCentroid])) #sigma & W80 height = np.max(lineFit) indexHeight = np.abs(lineFit - height).argmin() height50 = np.divide(height, 2.) height80 = np.divide(height, 5.) lineFitLeft = lineFit[:indexHeight] lineFitRight = lineFit[indexHeight:] indexWaveLeft50 = (np.abs(lineFitLeft - height50)).argmin() indexWaveRight50 = (np.abs(lineFitRight - height50)).argmin() + indexHeight waveDist50 = np.exp(waveNew[indexWaveRight50]) - np.exp( waveNew[indexWaveLeft50]) indexWaveLeft80 = (np.abs(lineFitLeft - height80)).argmin() indexWaveRight80 = (np.abs(lineFitRight - height80)).argmin() + indexHeight waveDist80 = np.exp(waveNew[indexWaveRight80]) - np.exp( waveNew[indexWaveLeft80]) sigmaLambda50 = waveDist50 / (2 * np.sqrt(2 * np.log(2))) sigmaInt50 = np.sqrt( np.power(sigmaLambda50, 2) - np.power(dLIn1, 2)) width80 = np.sqrt(np.power(waveDist80, 2) - np.power(dLIn1, 2)) nvar = np.nansum(lineFit >= 1e-5) disp = np.sqrt( np.divide( np.divide( np.nansum( np.multiply(lineFit, np.power(waveVel - centroidToT, 2))), nvar - 1), np.divide(np.nansum(lineFit), nvar))) if disp > dLIn1kms: dispIntr = np.sqrt(np.power(disp, 2) - np.power(dLIn1kms, 2)) else: dispIntr = disp #print(disp,dispIntr) sigmaCen['disp_' + lineName][indexCentroid] = disp sigmaCen['dispIntr_' + lineName][indexCentroid] = dispIntr sigmaCen['logDisp_' + lineName][indexCentroid] = np.log10(disp) sigmaCen['logDispIntr_' + lineName][indexCentroid] = np.log10(dispIntr) sigmaCen['sigma_' + lineName][indexCentroid] = cvP.lambdaVRad( lambdaRest + sigmaInt50, lambdaRest) #print(binID,indexWaveLeft50,indexWaveRight50,np.exp(waveNew[indexWaveRight50]),np.exp(waveNew[indexWaveLeft50]), # waveDist50,sigmaCen['sigma_'+lineName][indexCentroid]) sigmaCen['logSigma_' + lineName][indexCentroid] = np.log10( sigmaCen['sigma_' + lineName][indexCentroid]) sigmaCen['w80_' + lineName][indexCentroid] = cvP.lambdaVRad( lambdaRest + width80, lambdaRest) sigmaCen['logW80_' + lineName][indexCentroid] = np.log10( sigmaCen['w80_' + lineName][indexCentroid]) else: sigmaCen['w80_' + lineName][indexCentroid] = np.nan sigmaCen['logW80_' + lineName][indexCentroid] = np.nan sigmaCen['disp_' + lineName][indexCentroidx] = np.nan sigmaCen['dispIntr_' + lineName][indexCentroidx] = np.nan sigmaCen['logDisp_' + lineName][indexCentroidx] = np.nan sigmaCen['logDispIntr_' + lineName][indexCentroidx] = np.nan sigmaCen['sigma_' + lineName][indexCentroid] = np.nan sigmaCen['logSigma_' + lineName][indexCentroid] = np.nan sigmaCen['centroid_' + lineName][indexCentroid] = np.nan sigmaCen['logCentroid_' + lineName][indexCentroid] = np.nan sigmaCen['BIN_ID'][indexCentroid] = binID #if binID==33511: # sys.exit(0) counter += 1 return counter, sigmaCen
#!/usr/bin/env python # <examples/doc_model_loadmodelresult.py> import matplotlib.pyplot as plt import numpy as np from lmfit.model import load_modelresult data = np.loadtxt('model1d_gauss.dat') x = data[:, 0] y = data[:, 1] result = load_modelresult('gauss_modelresult.sav') print(result.fit_report()) plt.plot(x, y, 'bo') plt.plot(x, result.best_fit, 'r-') plt.show() # <end examples/doc_model_loadmodelresult.py>
def makeBFLineCube(self, cfg_par): cubeletsDir = cfg_par['general']['cubeletsDir'] cubeDir = cfg_par['general']['cubeDir'] momDir = cfg_par['general']['momDir'] if cfg_par['bestFitSel']['BFcube']['rotationID'] == True: modelCube = fits.open(cfg_par['bestFitSel']['BFcube']['modelCube']) mdC = modelCube[0].data rotMoM = np.zeros([mdC.shape[1], mdC.shape[2]]) * np.nan hdul = fits.open(cfg_par['general']['outTableName']) tabGen = hdul['BININFO'].data residuals = hdul['Residuals_' + cfg_par['gFit']['modName']].data ancels = hdul['Ancels' + cfg_par['gFit']['modName']].data rotArr = np.empty(len(ancels['BIN_ID'])) bF = np.array(residuals['bestFit'], dtype=int) wave, xAxis, yAxis, pxSize, noiseBin, vorBinInfo, dataSpec = tP.openVorLineOutput( cfg_par, cfg_par['general']['outVorLineTableName'], cfg_par['general']['outVorSpectra']) lineInfo = tP.openLineList(cfg_par) lineInfoAll = lineInfo.copy() index = np.where(lineInfo['BFCUbe'] == 0) fltr = np.array(index)[0] lineInfo.remove_rows(list(fltr)) lineNameStr = str(lineInfo['Name'][0]) if '[' in lineNameStr: lineName = lineNameStr.replace("[", "") lineName = lineName.replace("]", "") lineName = lineName + str(int(lineInfo['Wave'][0])) else: lineName = lineNameStr + str(int(lineInfo['Wave'][0])) lineNameName = lineNameStr + str(int(lineInfo['Wave'][0])) lineNameStr = np.array([lineNameStr + str(int(lineInfo['Wave'][0]))], dtype='a16') lineNamesStrAll = np.empty(len(lineInfoAll), dtype='a16') for ii in range(0, len(lineInfoAll['ID'])): #for ii in range(0,1): lineNameStrAll = str(lineInfoAll['Name'][ii]) if '[' in lineNameStrAll: lineNameAll = lineNameStrAll.replace("[", "") lineNameAll = lineNameAll.replace("]", "") lineNameAll = lineNameAll + str(int(lineInfoAll['Wave'][ii])) else: lineNameAll = lineNameStrAll + str(int( lineInfoAll['Wave'][ii])) lineNamesStrAll[ii] = str(lineNameStrAll + str(int(lineInfoAll['Wave'][ii]))) indexLine = np.where(lineNamesStrAll == lineNameStr)[0] modName = 'BF' f = fits.open(cubeDir + 'fitCube_' + modName + '.fits') dd = f[0].data hh = f[0].header mom = fits.open(momDir + 'g2/mom0_tot-' + lineName + '.fits') mm = mom[0].data indexFltr = np.broadcast_to(np.isnan(mm), dd.shape) dd[indexFltr] = np.nan #lambdaMin = np.log(cfg_par['gFit']['lambdaMin']) #lambdaMax = np.log(cfg_par['gFit']['lambdaMax']) #idxMin = int(np.where(abs(wave-lambdaMin)==abs(wave-lambdaMin).min())[0]) #idxMax = int(np.where(abs(wave-lambdaMax)==abs(wave-lambdaMax).min())[0]) lambdaMin = np.log(cfg_par['gFit']['lambdaMin']) lambdaMax = np.log(cfg_par['gFit']['lambdaMax']) idxMin = int( np.where(abs(wave - lambdaMin) == abs(wave - lambdaMin).min())[0]) idxMax = int( np.where(abs(wave - lambdaMax) == abs(wave - lambdaMax).min())[0]) wave = wave[idxMin:idxMax] dd = dd[idxMin:idxMax, :, :] velRangeMin = cvP.vRadLambda( -cfg_par['bestFitSel']['BFcube']['velRange'][0], lineInfo['Wave'][0]) - lineInfo['Wave'][0] velRangeMax = cvP.vRadLambda( cfg_par['bestFitSel']['BFcube']['velRange'][1], lineInfo['Wave'][0]) - lineInfo['Wave'][0] waveMin = np.log(lineInfo['Wave'][0] - velRangeMin) waveMax = np.log(lineInfo['Wave'][0] + velRangeMax) idxMin1 = int( np.where(abs(wave - waveMin) == abs(wave - waveMin).min())[0]) idxMax1 = int( np.where(abs(wave - waveMax) == abs(wave - waveMax).min())[0]) wave = wave[idxMin1:idxMax1] waveAng = np.exp(wave) vel = cvP.lambdaVRad(waveAng, lineInfo['Wave'][0]) + float( cfg_par['general']['velsys']) dd = dd[idxMin1:idxMax1, :, :] fitCube = np.empty([dd.shape[0], dd.shape[1], dd.shape[2]]) fitCubeMask = np.zeros([dd.shape[0], dd.shape[1], dd.shape[2]]) fitCubeMD = np.zeros([dd.shape[0], dd.shape[1], dd.shape[2]]) fitCubeMaskInter = np.zeros([dd.shape[0], dd.shape[1], dd.shape[2]]) vecSumMap = np.zeros([dd.shape[1], dd.shape[2]]) * np.nan lenghtLineMap = np.zeros([dd.shape[1], dd.shape[2]]) * np.nan for i in range(0, len(ancels['BIN_ID'])): match_bin = np.where(tabGen['BIN_ID'] == ancels['BIN_ID'][i])[0] if bF[i] == 0: modName = 'g1' elif bF[i] == 1: modName = 'g2' for index in match_bin: if np.sum(~np.isnan(dd[:, int(tabGen['PixY'][index]), int(tabGen['PixX'][index])])) != 0: result = load_modelresult( cfg_par['general']['runNameDir'] + 'models/' + modName + '/' + str(ancels['BIN_ID'][i]) + '_' + modName + '.sav') comps = result.eval_components() if modName == 'g1': fit = comps['g1ln' + str(indexLine[0]) + '_'] elif modName == 'g2': fit = comps['g1ln' + str(indexLine[0]) + '_'] + comps['g2ln' + str(indexLine[0]) + '_'] fitCube[:, int(tabGen['PixY'][index]), int(tabGen['PixX'][index])] = fit[idxMin1:idxMax1] if cfg_par['bestFitSel']['BFcube']['rotationID'] == True: mdSpec = mdC[:, int(tabGen['PixY'][index]), int(tabGen['PixX'][index])] mdSpec[mdSpec != 0] = 1. mdSpec = np.flipud(mdSpec) fitCubeMD[:, int(tabGen['PixY'][index]), int(tabGen['PixX'][index])] = mdSpec #centroid = ancels['centroid_'+lineName][i] #width = ancels['w80_'+lineName][i] fitSmall = fit[idxMin1:idxMax1] idxPeak = np.nanargmax(fitSmall) #print(idxPeak) idxLeft = int( np.where( abs(fitSmall[:idxPeak] - 10.) == abs(fitSmall[:idxPeak] - 10.).min())[0]) idxRight = int( np.where( abs(fitSmall[idxPeak:] - 10.) == abs(fitSmall[idxPeak:] - 10.).min())[0]) + idxPeak #print(idxLeft,idxRight) #velMin = centroid-(width/2.) #velMax = centroid+(width/2.) #indexVelMin = int(np.where(abs(vel-velMin)==abs(vel-velMin).min())[0]) #indexVelMax = int(np.where(abs(vel-velMax)==abs(vel-velMax).min())[0]) fitMask = np.zeros(len(fit[idxMin1:idxMax1])) fitMaskIntercect = np.zeros(len(fit[idxMin1:idxMax1])) #fitMask[indexVelMin:indexVelMax] = 1. fitMask[idxLeft:idxRight] = 1. lenghtLine = np.count_nonzero(fitMask == 1.) fitCubeMask[:, int(tabGen['PixY'][index]), int(tabGen['PixX'][index])] = fitMask #print(fitMask,mdSpec) vecCount = np.where((fitMask == 1.) & (mdSpec == 1.)) fitMaskIntercect[vecCount] = 1. vecSum = np.count_nonzero(fitMaskIntercect == 1.) fitCubeMaskInter[:, int(tabGen['PixY'][index]), int(tabGen['PixX'][index] )] = fitMaskIntercect vecSumMap[int(tabGen['PixY'][index]), int(tabGen['PixX'][index])] = vecSum lenghtLineMap[ int(tabGen['PixY'][index]), int(tabGen['PixX'][index] )] = lenghtLine / 100. * cfg_par['bestFitSel'][ 'BFcube']['rotationPercent'] if vecSum > (lenghtLine / 100. * cfg_par['bestFitSel'] ['BFcube']['rotationPercent']): rotArr[i] = 1. rotMoM[int(tabGen['PixY'][index]), int(tabGen['PixX'][index])] = 1. else: rotArr[i] = 0. rotMoM[int(tabGen['PixY'][index]), int(tabGen['PixX'][index])] = 0. else: fitCube[:, int(tabGen['PixY'][index]), int(tabGen['PixX'][index])] = np.nan fitCubeMask[:, int(tabGen['PixY'][index]), int(tabGen['PixX'][index])] = np.nan fitCubeMD[:, int(tabGen['PixY'][index]), int(tabGen['PixX'][index])] = np.nan fitCubeMaskInter[:, int(tabGen['PixY'][index]), int(tabGen['PixX'][index])] = np.nan vecSumMap[int(tabGen['PixY'][index]), int(tabGen['PixX'][index])] = np.nan lenghtLineMap[int(tabGen['PixY'][index]), int(tabGen['PixX'][index])] = np.nan waveAng = np.exp(wave) header = self.makeHeader(cfg_par, lineInfo['Wave'][0], hh, waveAng) outCubelet = cubeletsDir + str(lineNameName) + '_BF.fits' outCubeletMask = cubeletsDir + str(lineNameName) + '_BFMask.fits' outCubeletMaskfl = cubeletsDir + str( lineNameName) + '_BFMaskInter.fits' outCubeletMaskMD = cubeletsDir + str(lineNameName) + '_BFMD.fits' fits.writeto(outCubelet, np.flip(fitCube, axis=0), header, overwrite=True) fits.writeto(outCubeletMask, np.flip(fitCubeMask, axis=0), header, overwrite=True) fits.writeto(outCubeletMaskfl, np.flip(fitCubeMaskInter, axis=0), header, overwrite=True) fits.writeto(outCubeletMaskMD, np.flip(fitCubeMD, axis=0), header, overwrite=True) if cfg_par['bestFitSel']['BFcube']['rotationID'] == True: outMomRot = momDir + str(lineNameName) + '_RotMom.fits' outMomSum = momDir + str(lineNameName) + '_SumInter.fits' outMomLength = momDir + str(lineNameName) + '_LengthLine.fits' outMomDiff = momDir + str(lineNameName) + '_diffInter.fits' if 'CUNIT3' in header: del header['CUNIT3'] if 'CTYPE3' in header: del header['CTYPE3'] if 'CDELT3' in header: del header['CDELT3'] if 'CRVAL3' in header: del header['CRVAL3'] if 'CRPIX3' in header: del header['CRPIX3'] if 'NAXIS3' in header: del header['NAXIS3'] header['WCSAXES'] = 2 header['SPECSYS'] = 'topocent' header['BUNIT'] = 'Jy/beam' fits.writeto(outMomRot, rotMoM, header, overwrite=True) fits.writeto(outMomSum, vecSumMap, header, overwrite=True) fits.writeto(outMomLength, lenghtLineMap, header, overwrite=True) fits.writeto(outMomDiff, vecSumMap - lenghtLineMap, header, overwrite=True) t = Table(ancels) if 'RotMod' not in ancels.dtype.names: t.add_column(Column(rotArr, name='RotMod')) else: t.replace_column('RotMod', Column(rotArr, name='RotMod')) try: tt = Table(hdul['AncelsBF'].data) hdul['AncelsBF'] = fits.BinTableHDU(t.as_array(), name='AncelsBF') except KeyError as e: tt = fits.BinTableHDU.from_columns(t.as_array(), name='AncelsBF') hdul.append(tt) hdul.writeto(cfg_par['general']['outTableName'], overwrite=True) return