Translate

顯示具有 Python 標籤的文章。 顯示所有文章
顯示具有 Python 標籤的文章。 顯示所有文章

2014年7月18日 星期五

[Python] Coordinate Transform between Grid and Geographic (e.g HK1980 and WGS84)

https://pypi.python.org/pypi/CoorTransform_GirdGeographic
https://github.com/walter426/Python_CoorTransform_GirdGeographic

It is a python package refer to my previous VBA module, http://waltertech426.blogspot.com/2014/07/vba-coordinate-transform-from-hk1980-to.html.

This python package is to provide functions for coordinate transform from grid to geographic, or vice versa.
Only HK1980 and WGS84 are set as the default conversion.

#Coordinate Transformation according to http://www.geodetic.gov.hk/data/pdf/explanatorynotes_c.pdf

from math import * 


class CoorTransformer_GridAndGeographic:
#HK80 Datum is set as default
def __init__(self, E0 = 836694.05, N0 = 819069.8, Lng0 = 114.178556, Lat0 = 22.312133, m_0 = 1, M0 = 2468395.723, a = 6378388, e2 = 6.722670022 * pow(10,-3)):
#Initilalize Projection Parameter
self.E0 = E0
self.N0 = N0
self.Lng0 = Lng0 * pi / 180
self.Lat0 = Lat0 * pi / 180
self.m_0 = m_0
self.M0 = M0
self.a = a
self.e2 = e2
e4 = pow(e2, 2)


#Meridian distance Coefficients
self.A0 = 1 - (e2 / 4) - (3 * e4) / 64
self.A2 = (3.0 / 8.0) * (e2 + (e4 / 4.0))
self.A4 = (15.0 / 256.0) * e4


def MeridianDist(self, Lat):
return self.a * (self.A0 * Lat - self.A2 * sin(2 * Lat) + self.A4 * sin(4 * Lat))


#Coordinate Transform from grid to geographic in degree
def CoorTransform_GridToGeographic(self, Easting, Northing, accuracy = 9):
E0 = self.E0
N0 = self.N0
Lng0 = self.Lng0
Lat0 = self.Lat0
m_0 = self.m_0
M0 = self.M0
a = self.a
e2 = self.e2

#Convert from grid to geographic
#Calculate Lat_p by iteration of Meridian distance,
E_Delta = Easting - E0
N_delta = Northing - N0
Mp = (N_delta + M0) / m_0

Lat_min = -90 * pi / 180
Lat_max = 90 * pi / 180

accuracy = pow(10, -accuracy)

  #Newton 's method A0 = self.A0 A2 = self.A2 A4 = self.A4 Lat_p = (Lat_max + Lat_min) / 2 f = 1.1 while abs(f) > accuracy: f = Mp - self.MeridianDist(Lat_p) f_d1 = -a * (A0 - A2 * 2 * cos(2 * Lat_p) + A4 * 4 * cos(4 * Lat_p)) Lat_p = Lat_p - (f / f_d1)



t_p = tan(Lat_p)
v_p = a / pow((1.0 - e2 * pow(sin(Lat_p), 2)), (1 / 2))
p_p = (a * (1.0 - e2)) / pow((1 - e2 * pow(sin(Lat_p), 2)), (3 / 2))
W_p = v_p / p_p

Lng = Lng0 + (1 / cos(Lat_p)) * ((E_Delta / (m_0 * v_p)) - (1 / 6) * pow((E_Delta / (m_0 * v_p)), 3) * (W_p + 2 * pow(t_p, 2)))
Lat = Lat_p - (t_p / ((m_0 * p_p))) * (pow(E_Delta, 2) / ((2 * m_0 * v_p)))


return [Lng / pi * 180, Lat / pi * 180]


#Coordinate Transform from geographic in degree to grid
def CoorTransform_GeographicToGrid(self, Lng, Lat):
E0 = self.E0
N0 = self.N0
Lng0 = self.Lng0
Lat0 = self.Lat0
m_0 = self.m_0
M0 = self.M0
a = self.a
e2 = self.e2

#Convert Lat and Lng from degree to radian
Lng = Lng * pi / 180
Lat = Lat * pi / 180


#Convert from geographic to grid
Lng_Delta = Lng - Lng0
M = self.MeridianDist(Lat)

t_s = tan(Lat)
v_s = a / pow((1.0 - e2 * pow(sin(Lat), 2)), (1 / 2))
p_s = (a * (1.0 - e2)) / pow((1 - e2 * pow(sin(Lat), 2)), (3 / 2))
W_s = v_s / p_s

Easting = E0 + m_0 * v_s * (Lng_Delta * cos(Lat) + (1 / 6) * pow(Lng_Delta, 3) * pow(cos(Lat), 3) * pow(W_s - t_s, 2))
Northing = N0 + m_0 * ((M - M0) + v_s * (pow(Lng_Delta, 2) / 4) * sin(2 * Lat))


return [Easting, Northing]


#Coordinate Transform from HK1980 grid to WGS84 geographic in degree
def CoorTransform_Hk1980ToWgs84(self, Easting, Northing, Delimiter = ""):
LngLat_HK1980 = self.CoorTransform_GridToGeographic(Easting, Northing)

Lng_WGS84 = LngLat_HK1980[0] + (8.8 / 3600)
Lat_WGS84 = LngLat_HK1980[1] - (5.5 / 3600)


if Delimiter == "":
return [Lng_WGS84, Lat_WGS84]
else:
return str(Lng_WGS84) + Delimiter + str(Lat_WGS84)


#Coordinate Transform from WGS84 geographic in degree to HK1980 grid
def CoorTransform_Wgs84ToHK1980(self, Lng, Lat, Delimiter = ""):
Lng_HK1980 = Lng - (8.8 / 3600)
Lat_HK1980 = Lat + (5.5 / 3600)

EastNorth_HK1980 = self.CoorTransform_GeographicToGrid(Lng_HK1980, Lat_HK1980)


if Delimiter == "":
return EastNorth_HK1980
else:
return  str(EastNorth_HK1980(0)) & Delimiter & str(EastNorth_HK1980(1))

2014年2月25日 星期二

2014年1月24日 星期五

[VBA] Append table from MS ACCESS to SQLite

https://github.com/walter426/VbaUtilities/blob/master/SqlUtilities.bas

Due to the limitation of the ODBC connection, it is impossible to insert or update all records from access table into the SQLite table in one time. We need to do it in an indirect way like below,
1. Copy the table with data to be appended into a temporary .mdb database
2. Convert the mdb file to SQLite formet.(Java)
http://waltertech426.blogspot.com/2014/01/sqlite-convert-ms-access-mdb-file-into.html
3. Do the appending through SQLite script directly.(Python)
https://github.com/walter426/VbaUtilities/blob/master/SQLiteCmdParser.py

As below function required other functions I have written before, pls refer below repository
https://github.com/walter426/VbaUtilities/



'Execute SQLite Command Set
Public Function ExecuteSQLiteCmdSet(SQLiteDb_path As String, CmdSet As String) As String
    On Error GoTo Err_ExecuteSQLiteCmdSet
    
    Dim FailedReason As String

    If FileExists(SQLiteDb_path) = False Then
        FailedReason = SQLiteDb_path
        GoTo Exit_ExecuteSQLiteCmdSet
    End If
    
    
    'Create a SQLite Command file, and then parse it into the Python SQLite Command Parser for execution
    Dim SQLiteCmdFile_path As String
    Dim iFileNum_SQLiteCmd As Integer
    
    SQLiteCmdFile_path = [CurrentProject].[Path] & "\" & "SQLiteCmd.txt"
    iFileNum_SQLiteCmd = FreeFile()
    
    If FileExists(SQLiteCmdFile_path) = True Then
        Kill SQLiteCmdFile_path
    End If
    
    Open SQLiteCmdFile_path For Output As iFileNum_SQLiteCmd
    Print #iFileNum_SQLiteCmd, CmdSet
    Close #iFileNum_SQLiteCmd
    
    ShellCmd = "python " & [CurrentProject].[Path] & "\SQLiteCmdParser.py " & SQLiteDb_path & " " & SQLiteCmdFile_path
    Call ShellAndWait(ShellCmd, vbHide)

    Kill SQLiteCmdFile_path


Exit_ExecuteSQLiteCmdSet:
    ExecuteSQLiteCmdSet = FailedReason
    Exit Function

Err_ExecuteSQLiteCmdSet:
    Call ShowMsgBox(Err.Description)
    Resume Exit_ExecuteSQLiteCmdSet
    
End Function


'Append Table into a SQLite database
Public Function AppendTblToSQLite(Tbl_src_name As String, Tbl_des_name As String) As String
    On Error GoTo Err_AppendTblToSQLite
    
    Dim FailedReason As String
    
    If TableExist(Tbl_src_name) = False Then
        FailedReason = Tbl_src_name
        GoTo Exit_AppendTblToSQLite
    End If
    
    If TableExist(Tbl_des_name) = False Then
        FailedReason = Tbl_des_name
        GoTo Exit_AppendTblToSQLite
    End If
    
    
    'Create Db
    Dim TempDb_path As String
    TempDb_path = [CurrentProject].[Path] & "\TempDb.mdb"
    
    If FileExists(TempDb_path) = True Then
        Kill TempDb_path
    End If
    
    Call CreateDatabase(TempDb_path, dbLangGeneral)

    
    'Copy Table into the TempDb
    Dim SQL_cmd As String
    
    SQL_cmd = "SELECT * " & vbCrLf & _
                "INTO [" & Tbl_des_name & "]" & vbCrLf & _
                "IN '" & TempDb_path & "'" & vbCrLf & _
                "FROM [" & Tbl_src_name & "] " & vbCrLf & _
                ";"
    
    RunSQL_CmdWithoutWarning (SQL_cmd)


    'Convert TempDb into SQLite
    Dim SQLiteDb_path As String
    SQLiteDb_path = [CurrentProject].[Path] & "\TempDb.sqlite"
    
    If FileExists(SQLiteDb_path) = True Then
        Kill SQLiteDb_path
    End If
    
    Dim ShellCmd As String
    ShellCmd = "java -jar " & [CurrentProject].[Path] & "\mdb-sqlite.jar " & TempDb_path & " " & SQLiteDb_path
    Call ShellAndWait(ShellCmd, vbHide)
    
    SQL_cmd = "ATTACH """ & SQLiteDb_path & """ AS TempDb;" & vbCrLf & _
                "INSERT INTO [" & Tbl_des_name & "] SELECT * FROM TempDb.[" & Tbl_des_name & "];"
    
    Call ExecuteSQLiteCmdSet(GetLinkTblConnInfo(Tbl_des_name, "DATABASE"), SQL_cmd)
    
    Kill SQLiteDb_path
    Kill TempDb_path


Exit_AppendTblToSQLite:
    AppendTblToSQLite = FailedReason
    Exit Function

Err_AppendTblToSQLite:
    Call ShowMsgBox(Err.Description)
    Resume Exit_AppendTblToSQLite
    
End Function

2013年11月16日 星期六

[PyQt] Create Widget Grid(2D-array)

https://github.com/walter426/PyQtUtilities/

There are many GUI which require to display a group of widget(e.g. button, checkbox...) in a grid format.

Below is  an user-defined PyQt object to handle this kind of requirement,

Example:

self.WidgetList_QWG = QWidgetGrid('QCheckBox', '', Tbl_WidgetArgu_set, GridDirection = 0, MaxRowCnt = 15)
self.WidgetListt_scrollArea.setWidget(self.WidgetList_QWG)

Code:

from PyQt4.QtCore import *
from PyQt4.QtGui import *

import math


class QWidgetGrid(QWidget):
    def __init__(self, WidgetType, WidgetTypeName, WidgetArguSet, GridDirection = 0, MaxRowCnt = 0, MaxColCnt = 0):
        QWidget.__init__(self)
        
        if GridDirection > 1:
            return
        
        if MaxRowCnt == 0 and MaxColCnt == 0:
            return
            
        TblCnt = len(WidgetArguSet)
        
        if TblCnt <= 0:
            return
        
        
        if MaxRowCnt > 0 and MaxColCnt == 0:
            MaxColCnt = int(math.ceil(float(TblCnt)/float(MaxRowCnt)))
            
        elif MaxColCnt > 0 and MaxRowCnt == 0:
            MaxRowCnt = int(math.ceil(float(TblCnt)/float(MaxColCnt)))
                
        self.QGL = QGridLayout()
        

        tbl_idx = 0
        
        #From Top to Bottom, than Left to Right
        if GridDirection == 0:
            ColCnt = int(math.ceil(float(TblCnt)/float(MaxRowCnt)))
            
            for col_idx in range(0, ColCnt):
                RowCnt = MaxRowCnt

                if col_idx >= ColCnt - 1 and (TblCnt % MaxRowCnt) > 0:
                    RowCnt = TblCnt % MaxRowCnt
                
                for row_idx in range(0, RowCnt):
                    str_Widget_curr =  'self.' + WidgetTypeName + '_' + str(tbl_idx)
                    str_CreateWidget = str_Widget_curr + ' = ' + WidgetType + '('
                    
                    for k in range(0, len(WidgetArguSet[tbl_idx])):
                        str_CreateWidget += WidgetArguSet[tbl_idx][k] + ', '
                    
                    
                    str_CreateWidget = str_CreateWidget.rstrip(',') + ')'
                    exec(str_CreateWidget)     
                    exec('self.QGL.addWidget(' + str_Widget_curr + ', ' + str(row_idx) + ', ' + str(col_idx) + ')')
                    
                    tbl_idx += 1
        
        
        #From Left to Right, Top to Bottom
        elif GridDirection == 1:
            RowCnt = int(math.ceil(float(TblCnt)/float(MaxColCnt)))
            
            for row_idx in range(0, RowCnt):
                ColCnt = MaxColCnt

                if row_idx >= RowCnt - 1 and (TblCnt % MaxColCnt) > 0:
                    ColCnt = TblCnt % MaxColCnt
                
                for col_idx in range(0, ColCnt):
                    str_Widget_curr =  'self.' + WidgetTypeName + '_' + str(tbl_idx)
                    str_CreateWidget = str_Widget_curr + ' = ' + WidgetType + '('
                    
                    for k in range(0, len(WidgetArguSet[tbl_idx])):
                        str_CreateWidget += WidgetArguSet[tbl_idx][k] + ', '
                        
                        
                    str_CreateWidget = str_CreateWidget.rstrip(',') + ')'
                    exec(str_Widget_curr + ' = ' + WidgetType +'(' + str_CreateWidget + ')')     
                    exec('self.QGL.addWidget(' + str_Widget_curr + ', ' + str(row_idx) + ', ' + str(col_idx) + ')')
                    
                    tbl_idx += 1
        
        
        self.setLayout(self.QGL)
    
    def __del__(self):
        return

2013年7月17日 星期三

2013年6月9日 星期日

[Python] Tools to enter commands and capture log automatically from telnet batchly.

https://github.com/walter426/TelnetToLog

20130808:
Modify to support multiple arguments in templates


TelnetToLog
Creater: Walter Tsui

Description:
[Python]: Tools to enter commands and capture log automatically from telnet batchly.

1. Set the IP config in "TelnetToLog.py"
2. Set commands template in the folder, "template"
3. Create "log" folder, "list.txt" in the folder, "log". the "list.txt" declares the arguments will be passed into the template,
    where "CELL" are used in the template to be the argument passed here.
4. Modify "TelnetToLog_batch.bat" to process the batch DL