KeyError while perfoming solve of two equation - python

1st i need to get two equation of two longest line length
i put lenghths with eq in list like these [( length 1 , eq 1 ) ,.....]
sort list with reverse
get two equation of two longest line
when run the below code
from sympy import *
import math
class shape():
def __init__(self,T):
self.T=T
self.Ax = self.T[0][0]
self.Ay = self.T[0][1]
self.Bx = self.T[1][0]
self.By = self.T[1][1]
self.Cx = self.T[2][0]
self.Cy = self.T[2][1]
#Triangle:
self.C_dashx = 0.5 * (self.Ax + self.Bx)
self.C_dashy = 0.5 * (self.Ay + self.By)
self.B_dashx = 0.5 * (self.Ax + self.Cx)
self.B_dashy = 0.5 * (self.Ay + self.Cy)
self.A_dashx = 0.5 * (self.Bx + self.Cx)
self.A_dashy = 0.5 * (self.By + self.Cy)
if (self.Ax - self.A_dashx) == 0:
self.m_AA =0
else:
self.m_AA = (self.Ay - self.A_dashy) / (self.Ax - self.A_dashx)
if (self.Bx - self.B_dashx) == 0:
self.m_BB =0
else:
self.m_BB = (self.By - self.B_dashy) / (self.Bx - self.B_dashx)
if (self.Bx - self.B_dashx) == 0:
self.m_CC =0
else:
self.m_CC = (self.Cy - self.C_dashy) / (self.Bx - self.B_dashx)
def triangle_intersection(self):
self.x , self.y = symbols('x y')
self.eq1=Eq(self.m_AA*(self.x-self.Ax)+self.Ay-self.y,0)
self.eq2=Eq(self.m_BB*(self.x-self.Bx)+self.By-self.y,0)
self.solve_equation=solve([self.eq1,self.eq2],[self.x,self.y])
self.Zx=(self.solve_equation[self.x]).factor()
self.Zy=(self.solve_equation[self.y]).factor()
print(self.Zx,self.Zy)
def square_intersection(self):
self.Dx = self.T[3][0]
self.Dy = self.T[3][0]
# Line Solpe:
if (self.Bx - self.Ax) == 0:
self.m_AB = 0
else:
self.m_AB = (self.By - self.Ay) / (self.Bx - self.Ax)
if (self.Dx - self.Ax) == 0:
self.m_AD = 0
else:
self.m_AD = (self.Dy - self.Ay) / (self.Dx - self.Ax)
if (self.Cx - self.Bx) == 0:
self.m_BC = 0
else:
self.m_BC = (self.Cy - self.By) / (self.Cx - self.Bx)
if (self.Dx - self.Bx) == 0:
self.m_BD = 0
else:
self.m_BD = (self.Dy - self.By) / (self.Dx - self.Bx)
if (self.Dx - self.Cx) == 0:
self.m_CD = 0
else:
self.m_CD = (self.Dy - self.Cy) / (self.Dx - self.Cx)
if (self.Cx - self.Ax) == 0:
self.m_AC = 0
else:
self.m_AC = (self.Cy - self.Ay) / (self.Cx - self.Ax)
# Equation:
#### WHAT IS PROBLEM HERE###########
self.z, self.t = symbols('z t',positive=True)
self.eq_AB = Eq(self.m_AB * (self.z - self.Ax) + self.Ay - self.t,0)
self.eq_AC = Eq(self.m_AC * (self.z - self.Ax) + self.Ay - self.t,0)
self.eq_AD = Eq(self.m_AD * (self.z - self.Ax) + self.Ay - self.t,0)
self.eq_BC = Eq(self.m_BC * (self.z - self.Bx) + self.By - self.t,0)
self.eq_BD = Eq(self.m_BD * (self.z - self.Bx) + self.By - self.t,0)
self.eq_CD = Eq(self.m_CD * (self.z - self.Cx) + self.Cy - self.t,0)
self.length_AB = math.sqrt((self.Bx - self.Ax)**2 + (self.By - self.Ay)**2)
self.length_AC = math.sqrt((self.Cx - self.Ax)**2 + (self.Cy - self.Ay)**2)
self.length_AD = math.sqrt((self.Dx - self.Ax)**2 + (self.Dy - self.Ay)**2)
self.length_BC = math.sqrt((self.Cx - self.Bx)**2 + (self.Cy - self.By)**2)
self.length_BD = math.sqrt((self.Dx - self.Bx)**2 + (self.Dy - self.By)**2)
self.length_CD = math.sqrt((self.Dx - self.Cx)**2 + (self.Dy - self.Cy)**2)
#### WHAT IS PROBLEM HERE###########
self.lenghts = [(self.length_AB, self.eq_AB),(self.length_AC, self.eq_AC),(self.length_AD, self.eq_AD),(self.length_BC, self.eq_BC)
, (self.length_BD, self.eq_BD), (self.length_CD, self.eq_CD)]
self.newlenghts = sorted(self.lenghts,reverse=True)
self.max1=self.newlenghts[0][1]
self.max2=self.newlenghts[1][1]
self.solve_equation_sq = solve([self.max1, self.max2], [self.z, self.t])
print(self.solve_equation_sq)
self.Rx = (self.solve_equation_sq[self.z]).factor()
self.Ry = (self.solve_equation_sq[self.t]).factor()
print(self.Rx, self.Ry)
test=[(0,0),(4,0),(4,4),(0,4)]
a1=shape(test)
a1.triangle_intersection()
a1.square_intersection()
i got the below error
2.66666666666667 1.33333333333333
{z: t}
Traceback (most recent call last):
File "C:/Users/xxxxx/.PyCharmCE2019.3/config/scratches/programme logic function.py", line 127, in
a1.square_intersection()
File "C:/Users/xxxxx/.PyCharmCE2019.3/config/scratches/programme logic function.py", line 119, in square_intersection
self.Ry = (self.solve_equation_sq[self.t]).factor()
KeyError: t

If you print out the equations you are trying to solve you will see that they are the same so the only solution returned is {z:t} not {z:smthng, t:smthngelse}. So when you request the value of t it tells you that there is no t in the solution dictionary. Now you have to go back and see that you properly computed that equations that were to be solved.
Note, too, that SymPy has the Polygon/Triangle objects and might already have a method to answer the question that you are asking.

Related

Invalid index to scalar variable error when trying to use scipy.optimize.curve_fit

I have a function with different parameters that I want to optimize to fit some existing data.
The function runs fine on its own, but when I try to pass it through the scipy.optimize.curve_fit function, I get this error :
IndexError: invalid index to scalar variable.
I don't understand why the function would work on its own, and I would not get any errors.
What can I do ?
The original function used dictionnaries and I thought that might be the problem but I modified it and it still doesn't work.
This is the function I'm using :
def function_test(xy,X1,X2,X3,X4):
precip = xy\[0\]
potential_evap = xy\[1\]
nUH1 = int(math.ceil(X4))
nUH2 = int(math.ceil(2.0*X4))
uh1_ordinates = [0] * nUH1
uh2_ordinates = [0] * nUH2
UH1 = [0] * nUH1
UH2 = [0] * nUH2
for t in range(1, nUH1 + 1):
uh1_ordinates[t - 1] = s_curves1(t, X4) - s_curves1(t-1, X4)
for t in range(1, nUH2 + 1):
uh2_ordinates[t - 1] = s_curves2(t, X4) - s_curves2(t-1, X4)
production_store = X1*0.60# S
routing_store = X3*0.70# R
qsim = []
for j in range(2191):
if precip[j] > potential_evap[j]:
net_evap = 0
scaled_net_precip = (precip[j] - potential_evap[j])/X1
if scaled_net_precip > 13:
scaled_net_precip = 13.
tanh_scaled_net_precip = tanh(scaled_net_precip)
reservoir_production = (X1 * (1 - (production_store/X1)**2) * tanh_scaled_net_precip) / (1 + production_store/X1 * tanh_scaled_net_precip)
routing_pattern = precip[j]-potential_evap[j]-reservoir_production
else:
scaled_net_evap = (potential_evap[j] - precip[j])/X1
if scaled_net_evap > 13:
scaled_net_evap = 13.
tanh_scaled_net_evap = tanh(scaled_net_evap)
ps_div_x1 = (2 - production_store/X1) * tanh_scaled_net_evap
net_evap = production_store * (ps_div_x1) / \
(1 + (1 - production_store/X1) * tanh_scaled_net_evap)
reservoir_production = 0
routing_pattern = 0
production_store = production_store - net_evap + reservoir_production
percolation = production_store / (1 + (production_store/2.25/X1)**4)**0.25
routing_pattern = routing_pattern + (production_store-percolation)
production_store = percolation
for i in range(0, len(UH1) - 1):
UH1[i] = UH1[i+1] + uh1_ordinates[i]*routing_pattern
UH1[-1] = uh1_ordinates[-1] * routing_pattern
for j in range(0, len(UH2) - 1):
UH2[j] = UH2[j+1] + uh2_ordinates[j]*routing_pattern
UH2[-1] = uh2_ordinates[-1] * routing_pattern
groundwater_exchange = X2 * (routing_store / X3)**3.5
routing_store = max(0, routing_store + UH1[0] * 0.9 + groundwater_exchange)
R2 = routing_store / (1 + (routing_store / X3)**4)**0.25
QR = routing_store - R2
routing_store = R2
QD = max(0, UH2[0]*0.1+groundwater_exchange)
Q = QR + QD
qsim.append(Q)
return qsim

How to implement a zooming function with header and footer support in PagesTextEdit forked by dimkanovikov on github?

I am now currently working on a MS Word clone with Python 3 and want some effect with pagination support. I saw some implementations in https://forum.qt.io/topic/847/paginating-a-qtextedit/2, and I found the repository of dimkanovikov (https://github.com/dimkanovikov/PagesTextEdit). After that, I found the implementation of the translation for this code (https://github.com/BrightSoftwareFoundation/PagesTextEdit), but it is buggy, so I made a few changes to it. Here is a Minimal Reproducible Example:
QPageMetrics.py
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
class PageMetrics:
def __init__(self):
self.m_mmPageSize = QSizeF()
self.m_mmPageMargins = QMarginsF()
self.m_pxPageSize = QSizeF()
self.m_pxPageMargins = QMarginsF()
self.m_zoomRange = 0.0
def mmToInches(self, mm):
return mm * 0.039370147
def mmToPx(self, _mm, _x=True):
return self.mmToInches(_mm) * \
(qApp.desktop().logicalDpiX() if _x else
qApp.desktop().logicalDpiY())
def pageMetrics(self, _pageFormat=QPageSize.PageSizeId, _mmPageMargins=QMarginsF()):
self.update(_pageFormat, _mmPageMargins)
def setPxPageSize(self, _width, _height):
self.m_mmPageSize = QSizeF(_width, _height)
self.m_pxPageSize = QSizeF(self.mmToPx(self.m_mmPageSize.width(), True),
self.mmToPx(self.m_mmPageSize.height(), False))
def update(self, _pageFormat, _mmPageMargins=QMarginsF()):
self.m_pageFormat = _pageFormat
self.m_mmPageSize = QPageSize(self.m_pageFormat).rect(QPageSize.Unit.Millimeter).size()
self.m_mmPageMargins = _mmPageMargins
x = True
y = False
self.m_pxPageSize = QSizeF(self.mmToPx(self.m_mmPageSize.width(), x),
self.mmToPx(self.m_mmPageSize.height(), y))
self.m_pxPageMargins = QMarginsF(self.mmToPx(self.m_mmPageMargins.left(), x),
self.mmToPx(self.m_mmPageMargins.top(), y),
self.mmToPx(self.m_mmPageMargins.right(), x),
self.mmToPx(self.m_mmPageMargins.bottom(), y))
def pageFormat(self):
return self.m_pageFormat
def mmPageSize(self):
return self.m_mmPageSize
def mmPageMargins(self):
return self.m_mmPageMargins
def pxPageSize(self):
return QSizeF(self.m_pxPageSize.width(),
self.m_pxPageSize.height())
def pxPageMargins(self):
return QMarginsF(self.m_pxPageMargins.left(),
self.m_pxPageMargins.top(),
self.m_pxPageMargins.right(),
self.m_pxPageMargins.bottom())
def zoomIn(self, _zoomRange=float()):
self.m_zoomRange = _zoomRange
PagesTextEdit.py
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import QPageMetrics as pe
import sys
class PagesTextEdit(QTextEdit):
def __init__(self):
super().__init__()
self.m_document = QTextDocument()
self.m_usePageMode = True
self.m_addBottomSpace = True
self.m_showPageNumbers = True
self.m_pageNumbersAlignment = Qt.AlignTop | Qt.AlignRight
self.m_pageMetrics = pe.PageMetrics()
self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
self.aboutDocumentChanged()
self.textChanged.connect(self.aboutDocumentChanged)
self.verticalScrollBar().rangeChanged.connect(self.aboutVerticalScrollRangeChanged)
def setPageFormat(self, _pageFormat):
self.m_pageMetrics.update(_pageFormat)
self.repaint()
def setPageMargins(self, _margins):
self.m_pageMetrics.update(self.m_pageMetrics.pageFormat(), _margins)
self.repaint()
def paintEvent(self, _event):
self.updateVerticalScrollRange()
self.paintPageView()
self.paintPageNumbers()
super().paintEvent(_event)
def resizeEvent(self, _event):
self.updateViewportMargins()
super().resizeEvent(_event)
def updateViewportMargins(self):
self.viewportMargins = QMargins()
if self.m_usePageMode:
self.pageWidth = int(self.m_pageMetrics.pxPageSize().width())
self.pageHeight = int(self.m_pageMetrics.pxPageSize().height())
self.DEFAULT_TOP_MARGIN = int(20)
self.DEFAULT_BOTTOM_MARGIN = int(20)
self.leftMargin = int(0)
self.rightMargin = int(0)
if self.width() > self.pageWidth:
self.BORDERS_WIDTH = int(4)
self.VERTICAL_SCROLLBAR_WIDTH = int(self.verticalScrollBar().width()
if self.verticalScrollBar().isVisible()
else 0)
self.leftMargin = self.rightMargin = int((self.width() - self.pageWidth -
self.VERTICAL_SCROLLBAR_WIDTH - self.BORDERS_WIDTH) / 2)
self.topMargin = int(self.DEFAULT_TOP_MARGIN)
self.bottomMargin = int(self.DEFAULT_BOTTOM_MARGIN)
self.documentHeight = int(self.pageHeight * self.document().pageCount())
if (self.height() - self.documentHeight) > (self.DEFAULT_TOP_MARGIN + self.DEFAULT_BOTTOM_MARGIN):
self.BORDERS_HEIGHT = int(2)
self.HORIZONTAL_SCROLLBAR_HEIGHT = int(self.horizontalScrollBar().height()
if self.horizontalScrollBar().isVisible()
else 0)
self.bottomMargin = int(self.height() - self.documentHeight -
self.HORIZONTAL_SCROLLBAR_HEIGHT - self.DEFAULT_TOP_MARGIN -
self.BORDERS_HEIGHT)
self.viewportMargins = QMargins(self.leftMargin, self.topMargin, self.rightMargin, self.bottomMargin)
self.setViewportMargins(self.viewportMargins)
self.aboutUpdateDocumentGeometry()
def updateVerticalScrollRange(self):
if self.m_usePageMode:
self.pageHeight = int(self.m_pageMetrics.pxPageSize().height())
self.documentHeight = int(self.pageHeight * self.document().pageCount())
self.maximumValue = int(self.documentHeight - self.viewport().height())
if self.verticalScrollBar().maximum() != self.maximumValue:
self.verticalScrollBar().setMaximum(self.maximumValue)
else:
self.SCROLL_DELTA = int(800)
self.maximumValue = int(self.document().size().height() - self.viewport().size().height() +
(self.SCROLL_DELTA if self.m_addBottomSpace else 0))
if self.verticalScrollBar().maximum() != self.maximumValue:
self.verticalScrollBar().setMaximum(self.maximumValue)
def paintPageView(self):
if self.m_usePageMode:
self.pageWidth = float(self.m_pageMetrics.pxPageSize().width())
self.pageHeight = float(self.m_pageMetrics.pxPageSize().height())
self.p = QPainter(self.viewport())
self.spacePen = QPen(self.palette().window(), 9)
self.borderPen = QPen(self.palette().dark(), 1)
self.curHeight = float(self.pageHeight - (self.verticalScrollBar().value() %
int(self.pageHeight)))
self.canDrawNextPageLine = self.verticalScrollBar().value() != \
self.verticalScrollBar().maximum()
self.xValueF = self.pageWidth + (1 if (self.width() % 2 == 0) else 0)
self.xValue = int(self.xValueF)
self.horizontalDelta = int(self.horizontalScrollBar().value())
if (self.curHeight - self.pageHeight) >= 0:
self.p.setPen(self.borderPen)
self.p.drawLine(QLineF(float(0), self.curHeight - self.pageHeight,
self.xValueF, self.curHeight - self.pageHeight))
while self.curHeight <= self.height():
self.p.setPen(self.spacePen)
self.p.drawLine(QLineF(float(0), float(self.curHeight - 4),
float(self.width()), float(self.curHeight - 4)))
self.p.setPen(self.borderPen)
self.p.drawLine(QLineF(float(0), float(self.curHeight - 0),
self.xValueF, self.curHeight))
if self.canDrawNextPageLine:
self.p.drawLine(QLineF(float(0),
float(self.curHeight - 8),
float(self.pageWidth),
float(self.curHeight - 8)))
self.p.drawLine(QLineF(float(0 - self.horizontalDelta), float(self.curHeight - self.pageHeight),
float(0 - self.horizontalDelta), float(self.curHeight - 8)))
self.p.drawLine(QLineF(float(self.xValueF - self.horizontalDelta),
float(self.curHeight - self.pageHeight),
float(self.xValueF - self.horizontalDelta),
float(self.curHeight - 8)))
self.curHeight += self.pageHeight
if self.curHeight >= self.height():
self.p.setPen(self.borderPen)
self.p.drawLine(QLineF(float(0 - self.horizontalDelta), float(self.curHeight - self.pageHeight),
float(0 - self.horizontalDelta), float(self.height())))
self.p.drawLine(QLineF(float(self.xValueF - self.horizontalDelta),
float(self.curHeight - self.pageHeight),
float(self.xValueF - self.horizontalDelta),
float(self.height())))
def paintPageNumbers(self):
if (self.m_usePageMode and not self.m_pageMetrics.pxPageMargins().isNull() and
self.m_showPageNumbers):
self.pageSize = QSizeF(self.m_pageMetrics.pxPageSize())
self.pageMargins = QMarginsF(self.m_pageMetrics.pxPageMargins())
self.p = QPainter(self.viewport())
self.p.setFont(self.document().defaultFont())
self.p.setPen(QPen(self.palette().text(), 1))
self.curHeight = float(self.pageSize.height() - (self.verticalScrollBar().value() %
int(self.pageSize.height())))
self.leftMarginPosition = float(self.pageMargins.left() - self.pageMargins.right())
self.marginWidth = float(self.pageSize.width() - self.pageMargins.left() - self.pageMargins.right())
self.pageNumber = int(self.verticalScrollBar().value() / self.pageSize.height() + 1)
if self.curHeight - self.pageMargins.top() >= 0:
self.topMarginRect = QRectF(float(self.leftMarginPosition),
float(self.curHeight - self.pageSize.height()),
float(self.marginWidth),
float(self.pageMargins.top()))
self.paintPageNumber(self.p, self.topMarginRect, True, self.pageNumber)
while self.curHeight < self.height():
self.bottomMarginRect = QRect(int(self.leftMarginPosition),
int(self.curHeight - self.pageMargins.bottom()),
int(self.marginWidth),
int(self.pageMargins.bottom()))
self.paintPageNumber(self.p, self.bottomMarginRect, False, self.pageNumber)
self.pageNumber += 1
self.topMarginRect = QRect(int(self.leftMarginPosition), int(self.curHeight), int(self.marginWidth),
int(self.pageMargins.top()))
self.paintPageNumber(self.p, self.topMarginRect, True, self.pageNumber)
self.curHeight += self.pageSize.height()
self.p.end()
def paintPageNumber(self, _painter, _rect, _isHeader, _number):
if _isHeader:
if self.m_pageNumbersAlignment == Qt.AlignTop:
_painter.drawText(_rect, Qt.AlignVCenter | (self.m_pageNumbersAlignment ^ Qt.AlignTop),
str(_number))
else:
if self.m_pageNumbersAlignment == Qt.AlignBottom:
_painter.drawText(_rect, Qt.AlignVCenter | (self.m_pageNumbersAlignment ^ Qt.AlignBottom),
str(_number))
def aboutVerticalScrollRangeChanged(self, _minimum, _maximum):
self.updateViewportMargins()
self.scrollValue = int(self.verticalScrollBar().value())
if self.scrollValue > _maximum:
self.updateVerticalScrollRange()
def aboutDocumentChanged(self):
if self.m_document != self.document():
self.m_document = self.document()
self.document().documentLayout().update.connect(self.aboutUpdateDocumentGeometry)
def aboutUpdateDocumentGeometry(self):
self.documentSize = QSizeF(float(self.width() - self.verticalScrollBar().width()), float(-1))
if self.m_usePageMode:
self.pageWidth = (self.m_pageMetrics.pxPageSize().width())
self.pageHeight = (self.m_pageMetrics.pxPageSize().height())
self.documentSize = QSizeF(self.pageWidth, self.pageHeight)
if self.width() > self.pageWidth:
self.viewportMargins = QMargins(
int(int(self.width() - self.pageWidth - self.verticalScrollBar().width() - 2) / 2),
20,
int(int(self.width() - self.pageWidth - self.verticalScrollBar().width() - 2) / 2),
20
)
else:
self.viewportMargins = QMargins(0, 20, 0, 20)
if self.document().pageSize() != self.documentSize:
self.document().setPageSize(self.documentSize)
if self.document().documentMargin() != 0:
self.document().setDocumentMargin(0)
rootFrameMargin = self.m_pageMetrics.pxPageMargins()
rootFrameFormat = self.document().rootFrame().frameFormat()
self.setViewportMargins(self.viewportMargins)
if ((rootFrameFormat.leftMargin() != rootFrameMargin.left())
| (rootFrameFormat.topMargin() != rootFrameMargin.top())
| (rootFrameFormat.rightMargin() != rootFrameMargin.right())
| (rootFrameFormat.bottomMargin() != rootFrameMargin.bottom())):
rootFrameFormat.setLeftMargin(rootFrameMargin.left())
rootFrameFormat.setTopMargin(rootFrameMargin.top())
rootFrameFormat.setRightMargin(rootFrameMargin.right())
rootFrameFormat.setBottomMargin(rootFrameMargin.bottom())
self.document().rootFrame().setFrameFormat(rootFrameFormat)
Here are some few questions I want to ask:
How to implement a zooming function in the paged text edit like MS Word that zooms the whole page but not only text? I have tried different methods: using QGraphicsProxyWidget, delete the resizeEvent, try to implement a QScrollArea with setFrameRect, ... It crashes often, Process finished with exit code -1073740791 (0xC0000409) / RESTART: SHELL or RecursionError often appears.
How to change the page size? It does not crash, only for self.setPageSize(QPageSize.PageSizeId.A4) or .A5). For another size or custom one, it crashes with Process finished with exit code -1073740791 (0xC0000409) / RESTART: SHELL.
My page numbering / header and footer cannot be shown for an unknown reason. Can somebody help me to solve this?
Any comments / answers are appreciated!

Why am I not getting the value pairs for all three sequences?

I am trying to return all value pairs from three sequences, however I am only getting a single value pair for the first sequence. Does anyone know what happens?. The example sequences are "ALLKAIIAI", "AHHAKKAKLLA", "APPALLAIIKAMMA", see it in the code bellow:
def ComputeSeqs():
input_seq = ["ALLKAIIAI", "AHHAKKAKLLA", "APPALLAIIKAMMA"]
for sequence in input_seq:
ANDN920101={'A':4.35,'L':4.17,'R':4.38,'K':4.36,'N':4.75,
'M':4.52,'D':4.76,'F':4.66,'C':4.65,'P':4.44,
'Q':4.37,'S':4.50,'E':4.29,'T':4.35,'G':3.97,
'W':4.70,'H':4.63,'Y':4.60,'I':3.95,'V':3.95}
ARGP820101={'A':0.61,'L':1.53,'R':0.60,'K':1.15,'N':0.06,
'M':1.18,'D':0.46,'F':2.02,'C':1.07,'P':1.95,
'Q':0.0,'S':0.05,'E':0.47,'T':0.05,'G':0.07,
'W':2.65,'H':0.61,'Y':1.88,'I':2.22,'V':1.32}
aaindex_values = []
aaindex_listT = [ANDN920101, ARGP820101]
for i in aaindex_listT:
a_a = ((sequence.count("A") * i["A"])) / len(sequence)
c_c = ((sequence.count("C") * i["C"])) / len(sequence)
d_d = ((sequence.count("D") * i["D"])) / len(sequence)
e_e = ((sequence.count("E") * i["E"])) / len(sequence)
f_f = ((sequence.count("F") * i["F"])) / len(sequence)
g_g = ((sequence.count("G") * i["G"])) / len(sequence)
h_h = ((sequence.count("H") * i["H"])) / len(sequence)
i_i = ((sequence.count("I") * i["I"])) / len(sequence)
k_k = ((sequence.count("K") * i["K"])) / len(sequence)
l_l = ((sequence.count("L") * i["L"])) / len(sequence)
m_m = ((sequence.count("M") * i["M"])) / len(sequence)
n_n = ((sequence.count("N") * i["N"])) / len(sequence)
p_p = ((sequence.count("P") * i["P"])) / len(sequence)
q_q = ((sequence.count("Q") * i["Q"])) / len(sequence)
r_r = ((sequence.count("R") * i["R"])) / len(sequence)
s_s = ((sequence.count("S") * i["S"])) / len(sequence)
t_t = ((sequence.count("T") * i["T"])) / len(sequence)
v_v = ((sequence.count("V") * i["V"])) / len(sequence)
w_w = ((sequence.count("W") * i["W"])) / len(sequence)
y_y = ((sequence.count("Y") * i["Y"])) / len(sequence)
aaindex_comp = round(((a_a + c_c + d_d + e_e + f_f + g_g + h_h + i_i + k_k + l_l + m_m + n_n + p_p + q_q + r_r + s_s + t_t + v_v + w_w + y_y) / 20),3)
aaindex_values.append(aaindex_comp)
return aaindex_values
print(ComputeSeqs())
You need to initialize aaindex_values before the loop, and return it after the loop.
You're never creating nested lists for results of summing the multipliers from each dictionary in aaindex_listT. This is easiest done using a list comprehension. And you can loop over the dictionary and use sum() rather than creating 26 different variables.
def ComputeSeqs():
input_seq = ["ALLKAIIAI", "AHHAKKAKLLA", "APPALLAIIKAMMA"]
ANDN920101={'A':4.35,'L':4.17,'R':4.38,'K':4.36,'N':4.75,
'M':4.52,'D':4.76,'F':4.66,'C':4.65,'P':4.44,
'Q':4.37,'S':4.50,'E':4.29,'T':4.35,'G':3.97,
'W':4.70,'H':4.63,'Y':4.60,'I':3.95,'V':3.95}
ARGP820101={'A':0.61,'L':1.53,'R':0.60,'K':1.15,'N':0.06,
'M':1.18,'D':0.46,'F':2.02,'C':1.07,'P':1.95,
'Q':0.0,'S':0.05,'E':0.47,'T':0.05,'G':0.07,
'W':2.65,'H':0.61,'Y':1.88,'I':2.22,'V':1.32}
aaindex_listT = [ANDN920101, ARGP820101]
aaindex_values = []
for sequence in input_seq:
aaindex_comp = [sum(sequence.count(key) * value for key, value in i.items()) / len(sequence) for i in aaindex_listT]
aaindex_values.append(aaindex_comp)
return aaindex_values
print(ComputeSeqs())

offset a parallel line to a given line python

I want to draw parallel line to given X,Y coordinate below code helps to draw ,
import numpy as np
import matplotlib.pyplot as plt
x = [187, 879, 722, 322]
y = [341, 344, 112, 112]
newX = []
newY = []
def findIntesection(p1x, p1y, p2x, p2y, p3x,p3y, p4x, p4y):
dx12 = p2x - p1x
dy12 = p2y - p1y
dx34 = p4x - p3x
dy34 = p4y - p3y
denominator = (dy12*dx34-dx12*dy34)
t1 = ((p1x - p3x) * dy34 + (p3y - p1y) * dx34)/ denominator
t2 = ((p3x - p1x) * dy12 + (p1y - p3y) * dx12)/ -denominator;
intersectX = p1x + dx12 * t1
intersectY = p1y + dy12 * t1
if (t1 < 0): t1 = 0
elif (t1 > 1): t1 = 1
if (t2 < 0): t2 = 0
elif (t2 > 1): t2 = 1
return intersectX,intersectY
def normalizeVec(x,y):
distance = np.sqrt(x*x+y*y)
return x/distance, y/distance
def getEnlarged(oldX, oldY, offset):
num_points = len(oldX)
for j in range(num_points):
i = j - 1
if i < 0:
i += num_points
k = (j + 1) % num_points
vec1X = oldX[j] - oldX[i]
vec1Y = oldY[j] - oldY[i]
v1normX, v1normY = normalizeVec(vec1X,vec1Y)
v1normX *= offset
v1normY *= offset
n1X = -v1normY
n1Y = v1normX
pij1X = oldX[i] + n1X
pij1Y = oldY[i] + n1Y
pij2X = oldX[j] + n1X
pij2Y = oldY[j] + n1Y
vec2X = oldX[k] - oldX[j]
vec2Y = oldY[k] - oldY[j]
v2normX, v2normY = normalizeVec(vec2X,vec2Y)
v2normX *= offset
v2normY *= offset
n2X = -v2normY
n2Y = v2normX
pjk1X = oldX[j] + n2X
pjk1Y = oldY[j] + n2Y
pjk2X = oldX[k] + n2X
pjk2Y = oldY[k] + n2Y
intersectX,intersetY = findIntesection(pij1X,pij1Y,pij2X,pij2Y,pjk1X,pjk1Y,pjk2X,pjk2Y)
#print(intersectX,intersetY)
newX.append(intersectX)
newY.append(intersetY)
getEnlarged(x, y, 20)
plt.plot(x, y)
plt.plot(newX, newY)
plt.show()
This gives result as below
Here it is giving good result by drawing parallel line to each line of our trapezoidal shaped , but i want it to be a closed shape in place of open shape
i want to join the 1st and last coordinate so that it should form a closed shape. Any help will be appreciated .
Using approach from here
outer_ccw parameters combines vertex order and desired offset direction. For CCW order and outer polygon it is 1, for inner polygon it should be -1.
def makeOffsetPoly(oldX, oldY, offset, outer_ccw = 1):
num_points = len(oldX)
for curr in range(num_points):
prev = (curr + num_points - 1) % num_points
next = (curr + 1) % num_points
vnX = oldX[next] - oldX[curr]
vnY = oldY[next] - oldY[curr]
vnnX, vnnY = normalizeVec(vnX,vnY)
nnnX = vnnY
nnnY = -vnnX
vpX = oldX[curr] - oldX[prev]
vpY = oldY[curr] - oldY[prev]
vpnX, vpnY = normalizeVec(vpX,vpY)
npnX = vpnY * outer_ccw
npnY = -vpnX * outer_ccw
bisX = (nnnX + npnX) * outer_ccw
bisY = (nnnY + npnY) * outer_ccw
bisnX, bisnY = normalizeVec(bisX, bisY)
bislen = offset / np.sqrt((1 + nnnX*npnX + nnnY*npnY)/2)
newX.append(oldX[curr] + bislen * bisnX)
newY.append(oldY[curr] + bislen * bisnY)
x = [0, 100, 60, 40]
y = [0, 0, 50, 50]
makeOffsetPoly(x, y, 20)
print(newX, newY)
>>>[-29.424478775259594, 129.4244787752596, 66.79706177729007, 33.202938222709925]
[-14.14213562373095, -14.14213562373095, 64.14213562373095, 64.14213562373095]
Just append the first coordinates to the end of your lists.
x.append(x[0])
y.append(y[0])
newX.append(newX[0])
newY.append(newY[0])
Place this right before you plot. Here's my output

Vectorizing a Calculation - Bravais vector between pairs of points

The answer produced after vectorizing a calculation is very different from the original one, which I believe to be correct. Am I vectorizing this calculation correctly?
I'm dealing with an n-array (mean_pos) of shape (2, 91) and I was performing said calculation using for loops. Because for loops in Python are slow (and it's not the numpy way of doing stuff), I'm trying to vectorize the code.
With for loops:
def bravais_vector(natoms_i, mean_pos):
b_matrix = []
b_matrix_row = []
lx = mean_pos[0].max() - mean_pos[0].min()
ly = mean_pos[1].max() - mean_pos[1].min()
for i in range(natoms_i):
for j in range(natoms_i):
dist_ij_x = mean_pos[0][i] - mean_pos[0][j]
dist_ij_y = mean_pos[1][i] - mean_pos[1][j]
if dist_ij_x > lx/2:
dist_ij_x = -(lx - dist_ij_x)
if dist_ij_y > ly/2:
dist_ij_y = - (ly - dist_ij_y)
if dist_ij_x < -lx/2:
dist_ij_x = (lx + dist_ij_x)
if dist_ij_y < -ly/2:
dist_ij_y = (ly + dist_ij_y)
a2_opt = 2/np.sqrt(3) * dist_ij_y
a1_opt = dist_ij_x - 0.5 * a2_opt
b_matrix_row.append(np.array([ np.rint(a1_opt), np.rint(a2_opt) ]))
b_matrix.append(b_matrix_row)
b_matrix_row = []
return np.array(b_matrix)
Vectorized:
def bravais_vector(natoms_i, mean_pos):
b_matrix = []
b_matrix_row = []
lx = mean_pos[0].max() - mean_pos[0].min()
ly = mean_pos[1].max() - mean_pos[1].min()
mean_pos_x = np.reshape(mean_pos[0], (len(mean_pos[0]),1))
mean_pos_y = np.reshape(mean_pos[1], (len(mean_pos[1]),1))
tiled_mean_pos_x = np.tile(np.transpose(mean_pos_x), (len(mean_pos_x) , 1))
tiled_mean_pos_y = np.tile(np.transpose(mean_pos_y), (len(mean_pos_y) , 1))
dist_ij_x = mean_pos_x - tiled_mean_pos_x
dist_ij_y = mean_pos_y - tiled_mean_pos_y
dist_ij_x = np.where(dist_ij_x > lx/2, -(lx - dist_ij_x), dist_ij_x)
dist_ij_y = np.where(dist_ij_y > ly/2, -(ly - dist_ij_y), dist_ij_y)
dist_ij_x = np.where(dist_ij_x < -lx/2, lx + dist_ij_x, dist_ij_x)
dist_ij_y = np.where(dist_ij_y < -ly/2, ly + dist_ij_y, dist_ij_y)
a2_opt = np.rint(np.multiply(2 / (np.sqrt(3)), dist_ij_x))
a1_opt = np.rint(dist_ij_x - np.multiply(0.5, a2_opt))
return np.stack((a1_opt, a2_opt), axis=2)
Be careful because in the vectorized version, you wrote:
a2_opt = np.rint(np.multiply(2 / (np.sqrt(3)), dist_ij_x))
instead of (according to the first version)
a2_opt = np.rint(np.multiply(2 / (np.sqrt(3)), dist_ij_y))
I hope it helps.

Categories