예제 #1
0
 def translateForeign(self, txt):
     if len(txt) > 0:
         mlb = TrLib.ImportLabel(txt)
         if mlb is not None and len(mlb) > 0:
             self.ui.txt_mlb.setText(mlb)
             descr = TrLib.DescribeLabel(mlb)
             self.ui.lbl_system_info.setText("System: " + descr)
             return
     self.ui.lbl_system_info.setText("System: No translation")
     self.ui.txt_mlb.setText("No translation")
예제 #2
0
def RandomTests(TESTS, dim=3, N=10000, repeat=3, log_file=sys.stdout):
    nerr = 0
    id = str(threading.current_thread().name)
    log_file.write("%s\n" % LINE_SPLIT)
    log_file.write("Thread: %s, Transforming %d %dd-points...\n" %
                   (id, N, dim))
    for test in TESTS:
        if len(test) == 6:
            label_in, label_out, x, y, z, scale = test
            geoid = ""
        else:
            label_in, label_out, x, y, z, scale, geoid = test

        log_file.write("%s\n" % LINE_SPLIT)
        log_file.write("Label_in: %s, Label_out: %s\n" % (label_in, label_out))
        xyz = RandomPoints(N, dim, x, y, z, scale)
        if N <= 10:
            log_file.write("in:\n%s\n" % repr(xyz))
        elif HAS_NUMPY:
            log_file.write("Center of mass: %s\n" % xyz.mean(axis=0).tolist())
        nok = 0
        try:
            ct = TrLib.CoordinateTransformation(label_in, label_out, geoid)
        except Exception, msg:
            log_file.write(repr(msg) + "\n")
            sys.stderr.write(repr(msg) + "\n")
            msg = "Failed to open %s->%s, geoid: %s, last error: %d\n" % (
                label_in, label_out, geoid, TrLib.GetLastError())
            log_file.write(msg)
            sys.stderr.write(msg)
            nerr += 1
            if THREAD_TEST:
                return nerr
            continue
        for i in range(repeat):
            tstart = time.clock()
            try:
                xyz_out = ct.Transform(xyz)
            except Exception, msg:
                log_file.write(repr(msg) + "\n")
                sys.stderr.write(repr(msg) + "\n")
                msg = "From: %s To: %s, Last error: %d\n" % (
                    label_in, label_out, TrLib.GetLastError())
                log_file.write(msg)
                sys.stderr.write(msg)
                if N < 10:
                    sys.stderr.write("Input: %s\n" % repr(xyz))
                nerr += 1
                if THREAD_TEST:
                    return nerr
            else:
                nok += 1
                log_file.write("Forward running time: %.5f s\n" %
                               (time.clock() - tstart))
예제 #3
0
 def run(self):
     tstart = time.clock()
     if self.log_file is None:
         fp = sys.stdout
     else:
         fp = open(self.log_file, "w")
     if self.flag is not None:
         self.flag.clear()
     fp.write(
         "Hello world! This is thread %d. I perform %dD-tests. Mode is: %d"
         % (self.id, int(self.mode > 0) + 2, self.mode))
     if self.mode != 3:  #turn up the heat! Test having an open transformation in between lots of other stuff
         ct = TrLib.CoordinateTransformation("utm32Hwgs84_h_dvr90",
                                             "geoHed50_h_dvr90")
         fp.write(" *** %d ***" % self.id)
         x, y, z = ct.Transform(512200.1, 6143200.1, 100.0)
         fp.write(" %d: 1st done ***\n" % self.id)
     n = self.N  #+something random??
     while self.iterations > 0:
         fp.write(
             "This is thread %d, todo: %d. I perform %dD-tests. Mode is: %d\n"
             %
             (self.id, self.iterations, int(self.mode > 0) + 2, self.mode))
         if self.mode == 0:
             nerr = RandomTests.RandomTests_3D(n, log_file=NoOut())
         elif self.mode == 1:
             nerr = RandomTests.RandomTests_2D(n, log_file=NoOut())
         else:
             nerr = RandomTests.RandomTests(RandomTests.FH_TEST,
                                            3,
                                            n,
                                            log_file=NoOut())
         if nerr > 0:
             fp.write("Thread %d, mode %d, encountered %d errors!\n" %
                      (self.id, self.mode, nerr))
         time.sleep(0.01)
         self.iterations -= 1
     if self.mode != 3:
         x, y, z = ct.Transform(512200.1, 6143200.1, 100.0)
         ct.Close()
     if self.mode == 3:
         time.sleep(0.01)
     TrLib.TerminateThread()
     if self.mode == 3:
         time.sleep(0.01)
     if self.flag is not None:
         self.flag.set()
     tend = time.clock()
     fp.write("Thread %i finished. Running time %.2f s\n" %
              (self.id, tend - tstart))
     if self.log_file is not None:
         fp.close()
     return
예제 #4
0
def main(args): #progname, test_lib
	if "-no_threads" in args:
		i=args.index("-no_threads")
		args.pop(i)
		do_threads=False
	else:
		do_threads=True
	if len(args)<2:
		Usage()
	lib=args[1]
	lib_dir=os.path.dirname(lib)
	lib_obj=os.path.basename(lib)
	if len(args)>2:
		geoids=args[2]
	else:
		geoids=""
	now=time.asctime()
	nows=now.replace(" ","_").replace(":","_")
	log_name=LOG_FILE+"_"+nows+".log"
	log_fp=open(log_name,"w")
	sys.stdout=RedirectStdout(log_fp)
	sys.stderr=sys.stdout
	nerr=0
	print("Running test suite %s for the KMS transformation library at %s" %(PROG,now))
	print("System is: %s, architecture: %s" %(sys.platform,platform.architecture()))
	print("Python version: %s" %repr(sys.version))
	print("Initialising with shared-library: %s" %(lib))
	ok=TrLib.InitLibrary(geoids,lib_obj,lib_dir)
	if not ok:
		return 1
	TrLib.SetDebugMode()
	TrLib.SetMaxMessages(10000)
	print("Files in geoid-dir %s:\n%s" %(TrLib.GEOIDS,repr(os.listdir(TrLib.GEOIDS))))
	print LS
	mlb="utm32_ed50"
	print("Test if we can translate a minilabel:")
	try:
		wkt=TrLib.ExportLabel(mlb,"WKT")
	except:
		nerr+=1
	else:
		if wkt is None or len(wkt)==0:
			print("No recognisable output.")
		else:
			print("%s translates to:\n%s" %(mlb,wkt))
	print LS
	#allow unsafe transformations#
	TrLib.SetThreadMode(False) 
	try:
		nerr+=RandomTests.main(["RandomTests.py","-N",10000])
	except Exception,msg:
		print("Error:\n%s" %repr(msg))
		nerr+=1
예제 #5
0
def main(args): #progname, test_def, -lib libname (optional)
	progname=os.path.basename(args[0])
	IS_INIT=TrLib.IS_INIT
	if not IS_INIT:
		if "-lib" in args: #In this case we assume that input is the library that we want to test....
			lib=args[args.index("-lib")+1]
			lib=os.path.basename(lib)
			dir=os.path.dirname(lib)
			IS_INIT=TrLib.InitLibrary("",lib,dir)
		else:
			print("You can specify the TrLib-library to use by %s -lib <lib_path>" %progname)
			IS_INIT=TrLib.InitLibrary()
	if not IS_INIT:
		print("Could not initialize library...")
		print("Find a proper shared library and geoid dir and try again!")
		return -1
	print("Running %s at %s" %(progname,time.asctime()))
	print("Using TrLib v. %s" %TrLib.GetVersion())
	print("Shared library is: %s" %repr(TrLib.tr_lib))
	try:
		f=open(args[1])
	except:
		print("Test definition must be specified as first argument!")
		return -1
	job_dir=os.path.dirname(args[1])
	print("Using job definition in file %s" %args[1])
	for line in f:
		sline=line.split()
		if len(sline)==0:
			continue
		if sline[0][0]=="#":
			continue
		try:
			file_in,file_out,label_out,precision=line.split()
			precision=int(precision)
		except:
			print("Wrong definition:\n%s" %line)
			continue
		file_in=os.path.join(job_dir,file_in)
		file_out=os.path.join(job_dir,file_out)
		dir_out=os.path.dirname(file_out)
		if not os.path.exists(dir_out):
			print("Generating %s" %dir_out)
			os.mkdir(dir_out)
		if os.path.exists(file_in):
			TrLib.TransformFile(file_in,label_out,file_out,precision)
		else:
			print("%s does not exits!" %file_in)
	f.close()
	return 0
예제 #6
0
 def handleGeoUnitChange(self, geo_unit):
     self.geo_unit = geo_unit
     if TrLib.IsGeographic(str(self.cb_bshlm_system.currentText())):
         for field in self.input_bshlm:
             WidgetUtils.translateAngularField(field, geo_unit, precision=4)
     for field in self.output_bshlm_geo:
         WidgetUtils.translateAngularField(field, geo_unit, precision=4)
예제 #7
0
def main():
    tr = TrLib.CoordinateTransformation('geoEetrs89', 'geoHetrs89_h_dnn')

    lons = np.arange(LONMIN, LONMAX + DLON, DLON)
    lats = np.arange(LATMIN, LATMAX + DLAT, DLAT)

    cols = len(lons)
    rows = len(lats)

    grid = np.ndarray((rows, cols))

    for i, lat in enumerate(lats):
        for j, lon in enumerate(lons):
            I = rows - i - 1
            try:
                grid[I, j] = -tr.Transform(lon, lat, z=0.0)[2]
                if grid[I, j] > 1000.0:
                    grid[I, j] = NODATA
            except:
                grid[I, j] = NODATA

    ds = gdal.GetDriverByName('GTX').Create('dnn.gtx', cols, rows, 1,
                                            gdal.GDT_Float32)
    ds.SetGeoTransform((LONMIN, DLON, 0, LATMAX, 0, -DLAT))
    band = ds.GetRasterBand(1)
    band.SetNoDataValue(NODATA)
    band.WriteArray(grid)

    srs = osr.SpatialReference()
    srs.ImportFromEPSG(4258)
    ds.SetProjection(srs.ExportToWkt())
    band.FlushCache()
예제 #8
0
 def __init__(self, parent):
     WidgetBase.__init__(self, parent)
     self.setupUi(self)
     #convenient pointers#
     self.input_bshlm = [
         self.txt_bshlm_x1, self.txt_bshlm_y1, self.txt_bshlm_x2, self.txt_bshlm_y2]
     self.output_bshlm_geo = [
         self.txt_bshlm_lon1, self.txt_bshlm_lat1, self.txt_bshlm_lon2, self.txt_bshlm_lat2]
     # yep - bad naming, first field is the distance output/input
     self.output_bshlm_azimuth = [
         self.txt_bshlm_distance, self.txt_bshlm_azimuth1, self.txt_bshlm_azimuth2]
     self.input_bshlm_azimuth = self.output_bshlm_azimuth[:2]
     self.input_labels_bshlm = [self.lbl_bshlm_x, self.lbl_bshlm_y]
     self.derived_angular_output = self.output_bshlm_azimuth[1:]
     #SETUP BSHLM EVENT HANDLERS#
     # flag to set when we want the event handler to just return - e.g. when
     # removing a bad item...
     self._handle_system_change = True
     for field in self.input_bshlm + self.input_bshlm_azimuth:
         field.returnPressed.connect(self.doBesselHelmert)
     self.cb_bshlm_system.currentIndexChanged.connect(
         self.onBshlmSystemChanged)
     self.geo_unit = parent.geo_unit
     self.geo_unit_derived = parent.geo_unit_derived
     self.cache = BshlmCache()
     self.ed50_ellipsoid = TrLib.GetEllipsoidParametersFromDatum("ed50")
예제 #9
0
def main(args):
	progname=os.path.basename(args[0])
	IS_INIT=TrLib.IS_INIT
	if not IS_INIT:
		if "-lib" in args: #In this case we assume that input is the library that we want to test....
			libpath=args[args.index("-lib")+1]
			lib=os.path.basename(libpath)
			dir=os.path.dirname(libpath)
			IS_INIT=TrLib.InitLibrary("",lib,dir)
		else:
			print("You can specify the TrLib-library to use by %s -lib <lib_path>" %progname)
			IS_INIT=TrLib.InitLibrary()
	if not IS_INIT:
		print("Could not initialize library...")
		print("Find a proper shared library and geoid dir and try again!")
		return -1
	print("Running %s at %s" %(progname,time.asctime()))
	print("Using TrLib v. %s" %TrLib.GetVersion())
	print("Shared library is: %s" %repr(TrLib.tr_lib))
	if not os.path.exists(OUTPUT_DIR):
		os.mkdir(OUTPUT_DIR)
	if "-noout" in args:
		write_out=False
		print("Not using output to file!")
	else:
		write_out=True
	threads=[]
	RandomTests.SetThreadMode()
	for i in range(NTHREADS_2D):
		if write_out:
			fname=os.path.join(OUTPUT_DIR,"2dthread_%i.txt"%i)
		else:
			fname=None
		threads.append(BadGuy(i,NPOINTS,NITERATIONS,False,fname))
	for i in range(NTHREADS_3D):
		if write_out:
			fname=os.path.join(OUTPUT_DIR,"3dthread_%i.txt"%i)
		else:
			fname=None
		threads.append(BadGuy(NTHREADS_2D+i,NPOINTS,NITERATIONS,True,fname))
	for thread in threads:
		thread.start()
	while threading.activeCount()>1:
		print("Active threads: %i" %threading.activeCount())
		time.sleep(3)
	return 0
예제 #10
0
def main(args):
    progname = os.path.basename(args[0])
    IS_INIT = TrLib.IS_INIT
    if not IS_INIT:
        if "-lib" in args:  #In this case we assume that input is the library that we want to test....
            libpath = args[args.index("-lib") + 1]
            lib = os.path.basename(libpath)
            dir = os.path.dirname(libpath)
            IS_INIT = TrLib.InitLibrary("", lib, dir)
        else:
            print(
                "You can specify the TrLib-library to use by %s -lib <lib_path>"
                % progname)
            IS_INIT = TrLib.InitLibrary("")
    if not IS_INIT:
        print("Could not initialize library...")
        print("Find a proper shared library and geoid dir and try again!")
        return -1
    print("Running %s at %s" % (progname, time.asctime()))
    print("Using TrLib v. '%s'" % TrLib.GetVersion())
    print("Shared library is: %s" % repr(TrLib.tr_lib))
    N = 0
    if "-N" in args:
        try:
            N = int(args[args.index("-N") + 1])
        except:
            pass
    if N == 0:
        print(
            "You can input a parameter for the number of points as:\n%s -N <#points>"
            % (progname))
        N = 1000
        if HAS_NUMPY:
            N = 10000
    nerr = 0
    nerr += RandomTests(TEST_SYSTEMS_2D, 2, N, log_file=sys.stdout)
    nerr += RandomTests(TEST_SYSTEMS_3D, 3, N, log_file=sys.stdout)
    for i in range(3):
        nerr += RandomTests(FH_TEST, 3, N, log_file=sys.stdout)
    print("Errors: %d" % nerr)
    return nerr
예제 #11
0
    def onMLB(self):
        mlb = str(self.ui.txt_mlb.text())
        if len(mlb) > 0:
            descr = TrLib.DescribeLabel(mlb)
            wkt = TrLib.ExportLabel(mlb, "WKT")
            epsg = TrLib.ExportLabel(mlb, "EPSG")
            proj4 = TrLib.ExportLabel(mlb, "PROJ4")

            if wkt is not None and len(wkt) > 0:
                self.ui.txt_wkt.setText(wkt)
            else:
                self.ui.txt_wkt.setText("No translation")
            if epsg is not None and len(epsg) > 0:
                self.ui.txt_epsg.setText(epsg)
            else:
                self.ui.txt_epsg.setText("No translation")
            if proj4 is not None and len(proj4) > 0:
                self.ui.txt_proj4.setText(proj4)
            else:
                self.ui.txt_proj4.setText("No translation")
            self.ui.lbl_system_info.setText("System: " + descr)
예제 #12
0
def test():
    nerr = 0
    for text in TESTS:
        mlb = TrLib.ImportLabel(text)
        if mlb is None:
            print("\nUnable to translate %s" % text)
            nerr += 1
        else:
            print("\n%s\n-> %s" % (text, mlb))
            base = TESTS[text]
            if base is not None and mlb != base:
                nerr += 1
                print("Translation failed - should be: %s" % base)
            #Test inverse:
            out = TrLib.ExportLabel(mlb, "EPSG")
            if out is not None:
                print("To EPSG: %s->%s" % (mlb, out))
            else:
                print("No EPSG translation of %s" % mlb)

    return nerr
예제 #13
0
def main(args):
    progname = os.path.basename(args[0])
    IS_INIT = TrLib.IS_INIT
    if not IS_INIT:
        if "-lib" in args:  #In this case we assume that input is the library that we want to test....
            libpath = args[args.index("-lib") + 1]
            lib = os.path.basename(libpath)
            dir = os.path.dirname(libpath)
            IS_INIT = TrLib.InitLibrary("", lib, dir)
        else:
            print(
                "You can specify the TrLib-library to use by %s -lib <lib_path>"
                % progname)
            IS_INIT = TrLib.InitLibrary("")
    if not IS_INIT:
        print("Could not initialize library...")
        print("Find a proper shared library and geoid dir and try again!")
        return -1
    print("Running %s at %s" % (progname, time.asctime()))
    print("Using TrLib v. '%s'" % TrLib.GetVersion())
    print("Shared library is: %s" % repr(TrLib.tr_lib))
    nerr = test()
    print("Errors: %d" % nerr)
    return nerr
예제 #14
0
	def run(self):
		n=self.N #+something random??
		if self.log_file is None:
			fp=NoOut()
		else:
			fp=open(self.log_file,"w")
		while self.iterations>0:
			fp.write("This is thread %i\n" %(self.id+1))
			if self.is3d:
				nerr=RandomTests.RandomTests_3D(n,log_file=fp)
			else:
				nerr=RandomTests.RandomTests_2D(n,log_file=fp)
			if nerr>0:
				fp.write("Encountered %i errors!\n" %nerr)
			time.sleep(random.random()*0.1)
			self.iterations-=1
		fp.write("Thread finished\n")
		if self.log_file is not None:
			fp.close()
		TrLib.TerminateThread()
예제 #15
0
 def __init__(self, parent):
     WidgetBase.__init__(self, parent)
     self.parent = parent
     self.setupUi(self)
     #Event handlers#
     self.bt_python_run.clicked.connect(self.onPythonCommand)
     # Setup namespaces etc, log stufff.
     self.logPython("Python version:\n" + sys.version, color="green")
     self.logPython("TrLib version:\n" + TrLib.GetVersion(), color="green")
     namespace = {"loadPlugins": parent.loadPlugins, "mainWindow": parent}
     self.logPython("Handle to main window %s stored in name: mainWindow" %
                    repr(parent.__class__),
                    color="brown")
     self.python_console = EmbedPython.PythonConsole(namespace)
     self.python_console.executeCode("from TrLib import *")
     self.logPython(
         "from TrLib import *  - Loading namespace from TrLib.py",
         color="brown")
     self.logPython("Type 'example' to run example code", color="blue")
     self.logPython("Type 'clear' to clear output field", color="blue")
     # Determine what type the input text field should be and setup its
     # event handler....
     if HAS_QSCI:
         self.txt_python_in = Qsci.QsciScintilla(self)
         self.txt_python_in.setLexer(Qsci.QsciLexerPython())
         self.txt_python_in.setAutoIndent(True)
     else:
         self.txt_python_in = QTextEdit(self)
     self.layout().addWidget(self.txt_python_in)
     self.txt_python_in.keyPressEvent = self.onPythonKey
     if not HAS_QSCI:
         self.logPython(
             "Qscintilla not installed. Python input lexer will not work...",
             color="red")
     self.python_console.clearCache()
     self.txt_python_in.setWhatsThis("Enter/edit input python code here")
예제 #16
0
import numpy as np

from osgeo import gdal
from osgeo import osr

import TrLib

# Adjust accordingly...
TrLib.InitLibrary(r"C:\Data\Geoids2013", "trlib.dll",
                  r"C:\dev\TRLIB_v110\win64")
TrLib.SetMaxMessages(0)

LONMIN = 7.9
LONMAX = 15.3
LATMIN = 54.5
LATMAX = 57.8
DLON = 0.0020
DLAT = 0.0020

NODATA = -88.888  # GTX format NODATA value


def main():
    tr = TrLib.CoordinateTransformation('geoEetrs89', 'geoHetrs89_h_dnn')

    lons = np.arange(LONMIN, LONMAX + DLON, DLON)
    lats = np.arange(LATMIN, LATMAX + DLAT, DLAT)

    cols = len(lons)
    rows = len(lats)
예제 #17
0
	print LS
	try:
		TestFiles.main(["TestFiles.py",JOB_DEF])
	except Exception,msg:
		nerr+=1
		print("Error:\n%s" %repr(msg))
	print LS
	try:
		nerr+=TestProj.main(["TestProj.py"])
	except Exception,msg:
		nerr+=1
		print("Error:\n%s" %repr(msg))
	print LS
	#forbid unsafe transformations#
	if do_threads:
		TrLib.SetThreadMode(True)
		try:
			ThreadTest.main(["ThreadTest.py"])
		except Exception,msg:
			nerr+=1
			print("Error:\n%s" %repr(msg))
	else:
		print("-no_threads specified - will not run thread safety tests....")
	print LS
	print("Tests finished at %s" %time.asctime())
	print("Errors: %i" %nerr)
	return nerr

if __name__=="__main__":
	sys.exit(main(sys.argv))
	
예제 #18
0
                nok += 1
                log_file.write("Forward running time: %.5f s\n" %
                               (time.clock() - tstart))

        if nok == 0:
            continue
        log_file.write("Running inverse...\n")
        for i in range(repeat):
            tstart = time.clock()
            try:
                xyz_back = ct.InverseTransform(xyz_out)
            except Exception, msg:
                log_file.write(repr(msg) + "\n")
                sys.stderr.write(repr(msg) + "\n")
                msg = "From: %s To: %s, Last error: %d\n" % (
                    label_out, label_in, TrLib.GetLastError())
                log_file.write(msg)
                sys.stderr.write(msg)
                if N < 10:
                    sys.stderr.write("Input: %s\n" % repr(xyz_out))
                nerr += 1
                if THREAD_TEST:
                    return nerr
            else:
                log_file.write("Inverse running time: %.5f s\n" %
                               (time.clock() - tstart))
                if HAS_NUMPY and N <= 10:
                    err_xy = np.fabs(xyz[:, 0:2] - xyz_back[:, 0:2]).max()
                    if dim == 3:
                        err_z = np.fabs(xyz[:, 2] - xyz_back[:, 2]).max()
                    else:
예제 #19
0
def main(args):
    progname = os.path.basename(args[0])
    IS_INIT = TrLib.IS_INIT
    if not IS_INIT:
        if "-lib" in args:  #In this case we assume that input is the library that we want to test....
            libpath = args[args.index("-lib") + 1]
            lib = os.path.basename(libpath)
            dir = os.path.dirname(libpath)
            IS_INIT = TrLib.InitLibrary("", lib, dir)
        else:
            print(
                "You can specify the TrLib-library to use by %s -lib <lib_path>"
                % progname)
            IS_INIT = TrLib.InitLibrary()
    if not IS_INIT:
        print("Could not initialize library...")
        print("Find a proper shared library and geoid dir and try again!")
        return -1
    if "-trace" in args:
        threading.settrace(tracer)

    RandomTests.SetThreadMode()
    TrLib.SetThreadMode(False)
    now = time.asctime()
    nows = now.replace(" ", "_").replace(":", "_")
    log_name = LOG_FILE + "_" + nows + ".log"
    log_fp = open(log_name, "w")
    sys.stdout = RedirectStdout(log_fp)
    sys.stderr = sys.stdout
    if "-nruns" in args:
        nruns = int(args[args.index("-nruns") + 1])
    else:
        nruns = NRUNS
    if "-npoints" in args:
        npoints = int(args[args.index("-npoints") + 1])
    else:
        npoints = NPOINTS
    print("Running %s at %s" % (progname, time.asctime()))
    print("Using TrLib v. %s" % TrLib.GetVersion())
    print("Shared library is: %s" % repr(TrLib.tr_lib))
    finished_threads = 0
    nfemern = 0
    FH_flag = threading.Event()
    FH_flag.set()
    while finished_threads < nruns:
        if threading.activeCount() < KEEP_ALIVE:
            print("Active threads: %i" % threading.activeCount())
            finished_threads += 1
            rn = random.random()
            flag = None
            if rn < 0.4:
                mode = 0
            elif "-fehmarn" in args:
                if rn < 0.75:
                    mode = 1
                else:  #then start Fehmarn thread - which is problematic!
                    FH_flag.wait()
                    mode = 3
                    flag = FH_flag
                    nfemern += 1
            else:
                mode = 1
            new_thread = BadGuy(finished_threads, npoints, NITERATIONS, mode,
                                None, flag)
            new_thread.start()
            if nfemern > 0 and nfemern % 10 == 0:
                print("%d Fehmarn threads started." % nfemern)
    slept = 0
    while threading.activeCount() > 1:
        print("\nActive threads: %i\n" % threading.activeCount())
        if slept > 4:
            for thread in threading.enumerate():
                print("%s might be a zombie!" % thread.name)
        time.sleep(2)
        slept += 2
    return 0
예제 #20
0
    def doBesselHelmert(self):
        # Check if we need to update data....
        is_custom = self.chb_bshlm_custom_ellipsoid.isChecked()
        self.cache.is_valid = False
        self.logBshlm("", clear=True)
        if is_custom or str(self.cb_bshlm_system.currentText()) != self.cache.mlb:
            self.onBshlmSystemChanged(False)
        if not self.cache.valid_label:
            self.logBshlm("Invalid input label...", "red")
            self.clearOutput()
            return
        is_mode1 = self.rdobt_bshlm_mode1.isChecked()
        # Get needed input
        mlb = self.cache.mlb
        geo_mlb = self.cache.geo_mlb
        is_geo_in = is_custom or TrLib.IsGeographic(mlb)
        if is_mode1:
            coords, msg = WidgetUtils.getInput(
                self.input_bshlm, is_geo_in, z_fields=[], angular_unit=self.geo_unit)
            if len(coords) != 4:
                self.logBshlm("Input coordinate %d not OK.\n%s" %
                              (len(coords) + 1, msg), "red")
                self.input_bshlm[len(coords)].setFocus()
                self.clearOutput()
                return
            x1, y1, x2, y2 = coords

        else:
            coords, msg = WidgetUtils.getInput(
                self.input_bshlm[0:2], is_geo_in, z_fields=[], angular_unit=self.geo_unit)
            if len(coords) != 2:
                self.logBshlm("Station1 coordinates not OK.\n%s" % msg, "red")
                self.input_bshlm[len(coords)].setFocus()
                self.clearOutput()
                return
            input_data, msg = WidgetUtils.getInput(self.input_bshlm_azimuth, True, z_fields=[
                                                   0], angular_unit=self.geo_unit_derived)
            if len(input_data) != 2:
                self.logBshlm(
                    "Input distance and azimuth not OK.\n%s" % msg, "red")
                self.input_bshlm_azimuth[len(input_data)].setFocus()
                self.clearOutput()
                return
            x1, y1 = coords

            dist, a1 = input_data
        a = self.cache.axis
        f = self.cache.flattening
        #end get needed input#
        #transform to geo coords if needed#
        if not is_custom:
            try:
                ct = TrLib.CoordinateTransformation(mlb, geo_mlb)
            except:
                self.logBshlm("Input label not OK!", "red")
                self.clearOutput()
                return
            try:
                x1, y1, z = ct.Transform(x1, y1)
            except:
                msg = ""
                err = TrLib.GetLastError()
                if err in ERRORS:
                    msg = "\n%s" % ERRORS[err]
                self.logBshlm(
                    "Error in transformation of coords for station1" + msg, "red")
                self.clearOutput()
                return
        # display output of first transformation, x1,y1 should now alwyas be in
        # geo-coords#
        WidgetUtils.setOutput([x1, y1], self.output_bshlm_geo[
                              :2], True, z_fields=[], angular_unit=self.geo_unit)

        # Now get the other output from bshlm and transformations....
        if is_mode1:
            if not is_custom:
                try:  # transform to geographic
                    x2, y2, z = ct.Transform(x2, y2)
                except:
                    msg = ""
                    err = TrLib.GetLastError()
                    if err in ERRORS:
                        msg = "\n%s" % ERRORS[err]
                    self.logBshlm(
                        "Error in transformation of coords for station2" + msg, "red")
                    self.clearOutput()
                    return
            data = TrLib.BesselHelmert(a, f, x1, y1, x2, y2)
            if data[0] is not None:
                a1, a2 = data[1:]
                # WidgetUtils.setOutput(data,self.output_bshlm_azimuth,True,z_fields=[0],angular_unit=self.geo_unit_derived)
                self.output_bshlm_azimuth[0].setText("%.3f m" % data[0])
                self.output_bshlm_azimuth[1].setText(translateFromDegrees(
                    data[1], self.geo_unit_derived, precision=1))
                self.output_bshlm_azimuth[2].setText(translateFromDegrees(
                    data[2], self.geo_unit_derived, precision=1))
            else:
                self.message("Error: could not calculate azimuth!")
                self.clearOutput()
                return
        else:
            data = TrLib.InverseBesselHelmert(a, f, x1, y1, a1, dist)
            if data[0] is not None:
                x2, y2, a2 = data
                if not is_custom:
                    try:
                        x2_out, y2_out, z2 = ct.InverseTransform(x2, y2)
                    except:
                        msg = ""
                        err = TrLib.GetLastError()
                        if err in ERRORS:
                            msg = "\n%s" % ERRORS[err]
                        self.logBshlm(
                            "Error in transformation of coords for station2" + msg, "red")
                        self.clearOutput()
                        return
                else:
                    x2_out = x2
                    y2_out = y2
                # display result...
                WidgetUtils.setOutput([x2_out, y2_out], self.input_bshlm[
                                      2:], is_geo_in, z_fields=[], angular_unit=self.geo_unit)
                self.txt_bshlm_azimuth2.setText(translateFromDegrees(
                    a2, self.geo_unit_derived, precision=1))
            else:
                self.message(
                    "Error: could not do inverse Bessel Helmert calculation")
                self.clearOutput()
                return
        # always display ouput in geo field - even if not transformed
        self.cache.a1 = a1
        self.cache.a2 = a2
        WidgetUtils.setOutput([x2, y2],
                              self.output_bshlm_geo[2:], True, z_fields=[], angular_unit=self.geo_unit)
        self.cache.is_valid = True
        self.cache.mode = int(not is_mode1)
예제 #21
0
 def onBshlmSystemChanged(self, called_by_index_change=True):
     if not self._handle_system_change:
         return
     self.clearOutput()
     self.cache.is_valid = False  # signal no valid output YET!
     # will only be set to true if nothing goes wrong below....
     self.cache.valid_label = False
     is_custom = self.chb_bshlm_custom_ellipsoid.isChecked()
     self.logBshlm("", clear=True)
     if (is_custom):
         self.cache.is_custom = True
         self.cache.mlb = "custom"
         ell_data, msg = WidgetUtils.getInput(
             [self.txt_bshlm_axis, self.txt_bshlm_flattening], False)
         if len(ell_data) != 2 or ell_data[0] < 0 or ell_data[1] < 0:
             self.logBshlm("Bad ellipsoid data:\n%s" % msg, "red")
             self.cache.valid_label = False
             return
         self.cache.axis = ell_data[0]
         self.cache.flattening = ell_data[1]
         self.cache.valid_label = True
     else:
         self.cache.is_custom = False
         mlb = str(self.cb_bshlm_system.currentText())
         if len(mlb) == 0:
             return
         self.cache.mlb = mlb
         text = TrLib.DescribeLabel(mlb)
         self.lbl_bshlm_description.setText("%s" % text)
         labels = Minilabel.getSystemLabels(mlb)
         if labels is not None:
             for i in range(2):
                 self.input_labels_bshlm[i].setText(labels[i])
         if Minilabel.isProjWeaklyDefined(mlb):
             self.cache.proj_weakly_defined = True
             self.logBshlm(
                 "INFO: distance and azimuths will be calculated in ED50 datum", "blue")
             name, a, f = self.ed50_ellipsoid
             self.cache.geo_mlb = "geo_ed50"
         else:
             try:
                 dtm = TrLib.GetDatum(mlb)
                 name, a, f = TrLib.GetEllipsoidParametersFromDatum(dtm)
                 self.cache.geo_mlb = TrLib.Convert2Geo(mlb)
             except Exception, msg:
                 self.logBshlm("Invalid label:\n%s" % msg, "red")
                 if called_by_index_change:  # if called by handler which adds label to list
                     self._handle_system_change = False
                     self.cb_bshlm_system.removeItem(
                         self.cb_bshlm_system.currentIndex())
                     self.cb_bshlm_system.setEditText(mlb)
                     self._handle_system_change = True
                 return
         if name is not None:
             self.txt_bshlm_ellipsoid.setText(name)
             self.txt_bshlm_axis.setText("%.4f m" % a)
             if 0 < f < 1:
                 sf = 1 / f
             else:
                 sf = f
             self.txt_bshlm_flattening.setText("%.8f" % sf)
             self.cache.flattening = f
             self.cache.axis = a
             self.cache.ellipsoid = name
             self.cache.valid_label = True
         else:
             self.logBshlm(
                 "Invalid input label - unable to set ellipsoid data...", "red")
             if called_by_index_change:  # if called by handler which adds label to list
                 self._handle_system_change = False
                 self.cb_bshlm_system.removeItem(
                     self.cb_bshlm_system.currentIndex())
                 self.cb_bshlm_system.setEditText(mlb)
                 self._handle_system_change = True
             self.txt_bshlm_flattening.setText("")
             self.txt_bshlm_axis.setText("")
             self.cache.valid_label = False
예제 #22
0
def SetThreadMode(
):  #since  Fehmarn transformations are known NOT to be thread safe at the moment!
    global THREAD_TEST
    global TEST_SYSTEMS_3D
    TrLib.SetThreadMode()
    THREAD_TEST = True