code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
from tkinter import *
from profile import Profile
class Gui_ChangeProfile:
def __init__(self, gui):
self.root = Tk()
self.gui = gui
self.root.title("Profildaten")
self.root.wm_iconbitmap('@'+"campus.xbm")
self.root.geometry("700x500")
self.root.resizable(0,0)
#self.root.minsize = (700,500)
#self.root.maxsize = (730,500)
self.main_frame=Frame(self.root, height=680,width=680)
self.main_frame.pack(fill='x', padx=0, pady=0)
banner_frame=Frame(self.main_frame, height=510, width=300)
banner_frame.pack(fill="x", side="left", padx=0, pady=0)
image4=PhotoImage(file="sbanner2.gif", master=self.root)
label = Label(banner_frame, image=image4, borderwidth=0 )
label.image = image4
label.pack(side="left", padx=0, pady=0)
input_frame=Frame(self.main_frame, height=310,width=350)
input_frame.pack(padx=5, pady=5)
label_profile = Label(input_frame, text="Benutzerdaten ändern:", font="bold")
label_profile.grid(row=4, column=10, columnspan=2, pady=10, sticky=W)
label_username = Label(input_frame, text="Benutzername:")
label_username.grid(row=5, column=10, sticky=W)
self.e_username = Entry(input_frame)
self.e_username.grid(row=5, column=20)
label_name = Label(input_frame, text="Vorname:")
label_name.grid(row=10, column=10, sticky=W)
self.e_name = Entry(input_frame)
self.e_name.grid(row=10, column=20)
#self.e_name.focus_set()
label_lastname = Label(input_frame, text="Nachname:")
label_lastname.grid(row=20, column=10, sticky=W)
self.e_lastname = Entry(input_frame)
self.e_lastname.grid(row=20, column=20)
label_address = Label(input_frame, text="Adresse:")
label_address.grid(row=30, column=10, sticky=W)
self.e_address = Entry(input_frame)
self.e_address.grid(row=30, column=20)
label_plz = Label(input_frame, text="Postleitzahl:")
label_plz.grid(row=40, column=10, sticky=W)
self.e_plz = Entry(input_frame)
self.e_plz.grid(row=40, column=20)
label_city = Label(input_frame, text="Wohnort:")
label_city.grid(row=50, column=10, sticky=W)
self.e_city = Entry(input_frame)
self.e_city.grid(row=50, column=20)
label_phone = Label(input_frame, text="Telefonnummer:")
label_phone.grid(row=60, column=10, sticky=W)
self.e_phone = Entry(input_frame)
self.e_phone.grid(row=60, column=20)
label_email = Label(input_frame, text="E-Mail:")
label_email.grid(row=70, column=10, sticky=W)
self.e_email = Entry(input_frame)
self.e_email.grid(row=70, column=20)
button_frame = Frame(input_frame, height=50, width=350)
button_frame.grid(row=75, column=10, columnspan=2)
save_button = Button(button_frame, text="speichern", command=self.update ).grid(row=1, column=1)
cancel_button = Button(button_frame, text="abbrechen" , command=self.abbrechen).grid(row=1, column=2)
self.label_passwd = Label(input_frame, text="Passwort ändern:", font="bold")
self.label_passwd.grid(row=80, column=10, columnspan=2, pady=10, sticky=W)
label_old_passwd = Label(input_frame, text="Altes Passwort:")
label_old_passwd.grid(row=90, column=10, sticky=W)
self.e_oldpasswd = Entry(input_frame, show="*")
self.e_oldpasswd.grid(row=90, column=20)
label_passwd = Label(input_frame, text="Neues Passwort:")
label_passwd.grid(row=100, column=10, sticky=W)
self.e_passwd = Entry(input_frame, show="*")
self.e_passwd.grid(row=100, column=20)
label_passwd2 = Label(input_frame, text="Neues Passwort bestätigen:")
label_passwd2.grid(row=110, column=10, sticky=W)
self.e_passwd2 = Entry(input_frame, show="*")
self.e_passwd2.grid(row=110, column=20)
button_frame2 = Frame(input_frame, height=50, width=350)
button_frame2.grid(row=120, column=10, columnspan=2)
save_passwd = Button(button_frame2, text="speichern", command=self.updatepasswd ).grid(row=1, column=1)
cancel_button2 = Button(button_frame2, text="abbrechen" , command=self.abbrechen).grid(row=1, column=2)
self.label_report = Label(self.main_frame, text="", fg="red", font=("Helvetica", 10))
self.label_report.pack(pady=10)
self.profile = Profile(self.root, self.gui, self)
self.root.mainloop()
def deleteContent(self):
self.e_name.delete(0, END)
self.e_passwd.delete(0, END)
def abbrechen(self):
self.main_frame.destroy()
self.root.destroy()
def update(self):
self.profile.updateContent(self.e_username.get(), self.e_name.get(), self.e_lastname.get(), self.e_plz.get(), self.e_oldpasswd.get(), self.e_passwd.get(), self.e_passwd2.get(), self.e_address.get(), self.e_phone.get(), self.e_email.get(), self.e_city.get())
def updatepasswd(self):
self.profile.updatePasswd(self.gui.getUser(), self.e_oldpasswd.get(), self.e_passwd.get(), self.e_passwd2.get() )
def setReport(self, text):
self.label_report.config(text=text)
| Python |
from tkinter import *
from gui_login import Gui_Login
from gui_registration import Gui_Registration
from gui_grouplist import Gui_Grouplist
from groupList import GroupList
from teamList import TeamList
from gui_topframe import Gui_Topframe
from gui_group import Gui_Group
from gui_change_profile import Gui_ChangeProfile
from gui_messenger import Gui_Messenger
from userList import UserList
from gui_team import Gui_Team
class Gui:
def __init__(self):
self.root = Tk()
self.userList = UserList()
self.user = self.userList.getUser(0)
self.root.title("Mitfahrgelegenheit - Campus Minden")
self.root.config(bg="#f0f0f0");
self.root.wm_iconbitmap('@'+"campus.xbm")
self.createLogin()
def createLogin(self):
login = Gui_Login(self.root, self)
def createRegistration(self):
registration = Gui_Registration(self.root, self)
def createChangeProfile(self):
changeProfile = Gui_ChangeProfile(self)
def createMessenger(self):
messenger = Gui_Messenger(self)
def createGrouplist(self,user):
self.setUser(user)
self.grouplist = GroupList()
gui_grouplist = Gui_Grouplist(self.root, self, self.grouplist)
def createTopFrame(self):
self.gui_topframe = Gui_Topframe(self.root, self)
def createGroup(self, groupid):
gui_group = Gui_Group(self.root, self, self.grouplist.getGroupById(groupid))
def createTeam(self, group, team):
gui_team = Gui_Team(self.root, self, group, team)
def getUsers(self):
return self.userList
def getUser(self):
return self.user
def getUserById(self):
return self.user
def setUser(self, user):
self.user = user | Python |
import xml.etree.ElementTree as ET
from user import User
from userList import UserList
class MemberList:
userList = []
def __init__(self, typid):
self.typid = typid
def addXMLMembers(self, typid):
self.typid = typid
self.memberList = []
self.userList = UserList()
self.file = ET.parse("members.xml")
self.root = self.file.getroot()
groups = self.root.getchildren()
for group in groups:
grouptypid = group.attrib["id"]
if (grouptypid == self.typid ):
members = group.getchildren()
for member in members:
memberid = member.text
self.memberList.append(self.userList.getUserById(memberid))
def getMemberListbyIdAndTyp(self, typid):
newMemberList = []
for member in self.memberList:
if(member.getId() == typid):
newMemberList.append(member)
return newMemberList
def getSize(self):
a = 0
for member in self.memberList:
a += 1
return a
def getMemberList(self):
#print(id(self.memberList))
return self.memberList
def writeMember(self, userId, typId):
groupId = typId[:2]
xml_member = ET.Element("member")
xml_member.text = userId
self.file = ET.parse("members.xml")
self.root = self.file.getroot()
groups = self.root.getchildren()
for group in groups:
grouptypid = group.attrib["id"]
if (grouptypid == typId):
match = False
for member in group.getchildren():
if( member.findtext("member") == userId ):
match = True
if ( match == False ):
group.append(xml_member)
for group in groups:
grouptypid = group.attrib["id"]
if (grouptypid == groupId):
match = False
for member in group.getchildren():
if( member.findtext("member") == userId ):
match = True
if ( match == False ):
group.append(xml_member)
tree = ET.ElementTree(self.root)
tree.write("members.xml", xml_declaration=True, encoding='utf-8', method="xml")
def addUser(self, user, teamId):
match = False
for member in self.memberList:
if user.getId() == member.getId():
match = True
if( match == False ):
self.memberList.append(user)
self.writeMember(user.getId(), teamId)
print( 'member hinzugefügt' )
else:
print( 'member bereits vorhanden')
| Python |
from user import User
import xml.etree.ElementTree as ET
class UserList:
def __init__(self):
self.userList = []
self.userId = []
self.file = ET.parse("users.xml")
self.root = self.file.getroot()
self.users = self.root.getchildren()
for user in self.users:
userid = user.attrib['id']
name = user.findtext("name")
lastname = user.findtext("lastname")
username = user.findtext("username")
passwd = user.findtext("password")
contact = user.find("contact")
phone = contact.findtext("phone")
email = contact.findtext("email")
street = contact.findtext("street")
plz = contact.findtext("plz")
city = contact.findtext("city")
#groups = user.find("groups").getchildren()
user = User()
user.createXmlUser(userid, name, lastname, username, passwd, phone, email, street, plz, city)
# for group in groups:
# user.addGroup(group)
self.userList.append(user)
self.userId.append(userid)
def getLastUserId(self):
self.userId.sort(key=None, reverse=True)
userid = self.userId[0][1:] #erstes Zeichen entfernen
return( "u"+str(int(userid)+1))
def addUser(self, user):
self.userList.append(user)
def getUserList(self):
return self.userList
def getUser(self,position):
return self.userList[position]
def getUserById(self,userid):
result = ""
for user in self.userList:
if user.getId() == userid:
result = user
return result
def addUserXml(self,user):
xml_user = ET.Element('user', {"id" : user.getId()})
name = ET.SubElement(xml_user, "name")
name.text = user.getName()
lastname = ET.SubElement(xml_user, "lastname")
lastname.text = user.getLastname()
username = ET.SubElement(xml_user, "username")
username.text = user.getUsername()
password = ET.SubElement(xml_user, "password")
password.text = user.getPasswd()
contact = ET.SubElement(xml_user, "contact")
phone = ET.SubElement(contact, "phone")
phone.text = user.getTel()
email = ET.SubElement(contact, "email")
email.text = user.getEmail()
street = ET.SubElement(contact, "street")
street.text = user.getStreet()
plz = ET.SubElement(contact, "plz")
plz.text = user.getPlz()
city = ET.SubElement(contact, "city")
city.text = user.getCity()
groups = ET.SubElement(xml_user, "groups")
for user_groups in user.getGroupList():
group = ET.SubElement(groups, "group")
group.text = user_groups
self.root.append(xml_user)
tree = ET.ElementTree(self.root)
tree.write("users.xml", xml_declaration=True, encoding='utf-8', method="xml")
def updateUserXml(self, user):
for xmluser in self.users:
userid = xmluser.attrib['id']
if userid == user.getId():
self.root.remove(xmluser)
xml_user = ET.Element('user', {"id" : user.getId()})
name = ET.SubElement(xml_user, "name")
name.text = user.getName()
lastname = ET.SubElement(xml_user, "lastname")
lastname.text = user.getLastname()
username = ET.SubElement(xml_user, "username")
username.text = user.getUsername()
password = ET.SubElement(xml_user, "password")
password.text = user.getPasswd()
contact = ET.SubElement(xml_user, "contact")
phone = ET.SubElement(contact, "phone")
phone.text = user.getTel()
email = ET.SubElement(contact, "email")
email.text = user.getEmail()
street = ET.SubElement(contact, "street")
street.text = user.getStreet()
plz = ET.SubElement(contact, "plz")
plz.text = user.getPlz()
city = ET.SubElement(contact, "city")
city.text = user.getCity()
city = ET.SubElement(xml_user, "groups")
self.root.append(xml_user)
tree = ET.ElementTree(self.root)
tree.write("users.xml", xml_declaration=True, encoding='utf-8', method="xml")
| Python |
from wall import Wall
from memberList import MemberList
class Team:
typ = "team"
def __init__(self, teamid, name):
self.teamid = teamid
self.name = name
def addXmlTeam(self):
self.addXmlMemberList()
self.addXmlWall()
def addXmlWall(self):
self.wall = Wall(self.teamid, self.typ)
self.wall.createWall()
def addXmlMemberList(self):
self.members = MemberList(self.teamid)
self.members.addXMLMembers(self.teamid)
def getId(self):
return self.teamid
def getName(self):
return self.name
def getWall(self):
return self.wall
def getMembersList(self):
return self.members.getMemberList()
def getMembers(self):
return self.members
| Python |
from gui import Gui
from messenger import Messenger
from groupList import GroupList
from userList import UserList
from user import User
'''
Mitfahrgelegenheit - ein Python/XML-Projekt an der FH Bielefeld am Campus Minden
Autoren:
- Malte Flender
- Jerome Goncalvez
- Sebastian Hartmann
- Marius Krause
- Rico Schwarck
Lizenz: Open Source
'''
#groupList = GroupList()
#print(groupList.getGroup(1).getTeamList().getTeam(1))
gui = Gui()
'''
userList = UserList()
userList.getLastUserId(
user_a = User()
user_a.createXmlUser("u00006", "Rico", "Schwarck", "RiSc", "00212", "33178", "Fahrer", "132", "123", "213")
userList.addUser(user_a)
#users = userList.getUserList()
#for user in users:
# print(user.getId())
# print(user.getGroupList())
userList.addUserXml(user_a)
'''
| Python |
from tkinter import *
class Gui_Group:
def __init__(self, root, gui, group):
self.gui = gui
self.root = root
self.group = group
self.root.geometry("870x650")
self.main_frame=Frame(self.root, height=600, width=850, bg="#f0f0f0")
self.main_frame.pack( padx=10, pady=10)
self.main_frame.propagate(0)
self.navigation_frame=Frame(self.main_frame, height=20, width=600, bg="#f0f0f0")
self.navigation_frame.pack( padx=10, pady=10, fill='x' )
self.navigation_frame.grid_propagate(0)
button_grouplist = Button(self.navigation_frame, text="Gruppenübersicht", borderwidth=0, bg="#f0f0f0", activebackground="#f0f0f0", command=self.create_grouplist)
button_grouplist.grid(row = 0, column = 0, sticky = W, padx = 0)
label_title = Label(self.navigation_frame, text="- "+ self.group.getName(), bg="#f0f0f0")
label_title.grid( row = 0, column = 1, sticky = W, padx = 0)
'''
//////////////////////////////
'''
self.content_frame=Frame(self.main_frame, height=20, width=600, bg="#f0f0f0")
self.content_frame.pack( pady=0 )
self.content_frame.propagate(0)
label_title = Label(self.content_frame, text=" Mitglieder: "+str(self.group.getMemberCount()), bg="#f0f0f0")
label_title.grid( row = 5, column = 0, sticky= N+W )
#pinn_write_label = Label(self.content_frame, text="Etwas an die Pinnwand heften",bg="#f0f0f0")
#pinn_write_label.grid(row=5, column=5)
listlabel_title = Label(self.content_frame, text="Teams", bg="#f0f0f0")
listlabel_title.grid( row = 6, column = 0, padx=10, sticky= W )
self.left_frame=Frame(self.content_frame, height=500,width=225, bg="#f0f0f0")
self.left_frame.grid( row = 10, column = 0, padx=10, pady=10, sticky = S )
self.left_frame.grid_propagate(0)
self.listbox = Listbox(self.left_frame, height=18, width=20, font="Verdana", bg="white")
self.listbox.grid( row = 10, column = 0, pady = 0, sticky= W )
for team in self.group.getTeams():
self.listbox.insert(END, team.getName())
button_frame = Frame(self.left_frame, height=230,width=300, bg="#f0f0f0" )
button_frame.grid( row = 20, column = 0, sticky= E )
join_button = Button(button_frame, text="Team anzeigen", command=self.showTeam, borderwidth=2, background="#f0f0f0")
join_button.pack(side="left")
member_button = Button(button_frame, text="Mitglieder anzeigen", command=self.showMember)
member_button.pack(side="right")
'''
//////////////////////////////
'''
self.center_frame=Frame(self.content_frame, height=500, width=280, bg="#f0f0f0")
self.center_frame.grid( row = 10, column = 10, pady=0, sticky = S )
self.center_frame.grid_propagate(0)
self.center_button_frame=Frame(self.center_frame, height=480,width=280, bg="#f0f0f0")
self.center_button_frame.grid( row = 10, column = 0, sticky = S )
#member_button = Button(self.center_button_frame, text="Mitglieder anzeigen", command=self.showMember)
#member_button.grid(row=1, column=1)
#self.full_frame=Frame(self.center_button_frame, height=100,width=280)
#self.full_frame.grid(row=2, column=1)
#self.pinn_entry = Entry(self.center_button_frame, bg = "yellow", width=30)
#self.pinn_entry.grid(row=3, column=1)
self.pinn_text = Text(self.center_button_frame,height=21, width=33, bg="white")
self.pinn_text.grid(row=3, column=1)
pinn_button = Button(self.center_button_frame, bg = "#f0f0f0", text = "Senden", command=self.posten, width=37)
pinn_button.grid(row=4, column=1)
'''
//////////////////////////////
'''
pinn_write_label = Label(self.content_frame, text="Etwas an die Pinnwand heften",bg="#f0f0f0")
pinn_write_label.grid(row=5, column=10, sticky = W)
label_wall_title = Label(self.content_frame, text="Pinnwand", bg="#f0f0f0" )
label_wall_title.grid( row = 5, column = 20, sticky = W )
self.right_frame=Frame(self.content_frame, height=600, width=350, bd=1, relief=SUNKEN, bg="#f0f0f0")
self.right_frame.grid( row = 10, column = 20, pady=10, sticky = N )
self.right_frame.grid_propagate(0)
numberMassage = self.group.getWall().countMassage() *82
self.canv = Canvas(self.right_frame, bg="#f0f0f0" )
self.canv.config(width=300, height=400)
self.canv.config(scrollregion=(0,0,0, numberMassage))
self.canv.config(highlightthickness=0)
self.sbar = Scrollbar(self.right_frame, bg="#f0f0f0" )
self.sbar.config(command=self.canv.yview)
self.canv.config(yscrollcommand=self.sbar.set)
self.sbar.pack(side=RIGHT, fill=Y)
self.canv.pack(side=LEFT, expand=YES, fill=BOTH)
self.frame=Frame(self.canv, bg="#f0f0f0" )
self.canv.create_window(0, 0, window = self.frame, width = 285, anchor ="nw")
wall = self.group.getWall().getMessageList()
i= 0
for messages in wall:
i+=10
label_sender = Label(self.frame, bg="#f0f0f0", text=self.gui.getUsers().getUserById(messages.getSender()).getName())
label_sender.grid(row = i, column = 0, sticky = W )
label_date = Label(self.frame, bg="#f0f0f0", text=messages.getDate())
label_date.grid(row = i, column = 1, sticky = E )
msg = Message(self.frame, bg="#f0f0f0", text = messages.getContent())
msg.config(width=285)
msg.grid(row = i+1, column = 0, columnspan=2, sticky = W )
msg = Message(self.frame,bg="#f0f0f0", text ="____________________________________________")
msg.config(width=285)
msg.grid(row = i+2, column = 0, columnspan=2 )
self.canvas = self.canv
self.root.mainloop()
def posten(self):
content = self.pinn_text.get('0.0',END)
""" if OHNE FUNKTION """
if content != "":
self.group.getWall().writeMassage(self.gui.getUser().getId(), content)
self.main_frame.destroy()
self.gui.createGroup(self.group.getId())
else:
print("leer")
def showTeam(self):
teamname = self.listbox.get("active")
for team in self.group.getTeams():
if team.getName() == teamname:
self.main_frame.destroy()
self.gui.createTeam(self.group, team)
def showMember(self):
print("asd")
root = Tk()
root.title(self.group.getName() + "")
root.config(bg="#f0f0f0");
root.geometry("230x330")
root.wm_iconbitmap('@'+"campus.xbm")
root.resizable(0, 0)
text_label = Label(root, text="Mitgliederliste", bg="#f0f0f0")
text_label.pack()
listbox = Listbox(root, height=15, width=20, font="Verdana", bg="#ffffff")
listbox.pack()
for member in self.group.getMembersList():
listbox.insert(END, member.getName())
#info_button = Button(root, text="Benutzerinfo", height=15, width=20)
#info_button.pack()
root.mainloop()
def create_grouplist(self):
self.main_frame.destroy()
self.gui.createGrouplist(self.gui.getUser())
| Python |
from user import User
class Profile():
userMinLength = 6
passwdMinLength = 6
def __init__(self, root, gui, gui_Profile):
self.root = root
self.gui = gui
self.gui_Profile = gui_Profile
self.user = self.gui.getUser()
self.gui_Profile.e_username.insert(0,self.user.getUsername())
self.gui_Profile.e_name.insert(0,self.user.getName())
self.gui_Profile.e_lastname.insert(0,self.user.getLastname())
self.gui_Profile.e_address.insert(0,self.user.getAddress())
self.gui_Profile.e_plz.insert(0,self.user.getPlz())
self.gui_Profile.e_city.insert(0,self.user.getCity())
self.gui_Profile.e_phone.insert(0,self.user.getPhone())
self.gui_Profile.e_email.insert(0,self.user.getEmail())
def updateContent(self, username, name, lastname, plz,oldpasswd, passwd, passwdconfirm, address, phone, email, city):
self.gui_Profile.label_report.config(fg="red")
self.username = username
self.name = name
self.lastname = lastname
self.plz = plz
self.oldpasswd = oldpasswd
self.passwd = passwd
self.passwdconfirm = passwdconfirm
self.address = address
self.phone = phone
self.email = email
self.city = city
''' test self.username max/min lenght '''
if self.username == "":
self.gui_Profile.setReport("Bitte gib einen Benutzernamen ein.")
self.gui_Profile.e_username.focus_set()
elif len(self.username) < self.userMinLength:
print(self.username)
print( len(self.username))
self.gui_Profile.setReport("Der Username muss mindestens " + str(self.userMinLength) + " Zeichen lang sein.")
self.gui_Profile.e_username.focus_set()
""" test self.name """
elif self.name == "":
self.gui_Profile.setReport("Bitte gib einen Namen ein.")
self.gui_Profile.e_name.focus_set()
elif not self.name.isalpha():
self.gui_Profile.setReport("Der Name darf nur Buchstaben enthalten.")
self.gui_Profile.e_name.focus_set()
""" test self.lastname """
elif self.lastname == "":
self.gui_Profile.setReport("Bitte gib einen Nachnamen ein.")
self.gui_Profile.e_lastname.focus_set()
elif not self.lastname.isalpha():
self.gui_Profile.setReport("Der Nachname darf nur Buchstaben enthalten.")
self.gui_Profile.e_lastname.focus_set()
'''
""" test old passwd """
elif self.oldpasswd == "":
self.gui_Profile.setReport("Bitte gib dein aktuelles Passwort ein.")
self.gui_Profile.e_oldpasswd.focus_set()
elif self.oldpasswd != self.user.getPasswd():
self.gui_Profile.setReport("Das alte Passwort ist nicht korrekt.")
self.gui_Profile.e_passwd2.focus_set()
""" test self.passwd minlength and confirm right """
elif self.passwd == "":
self.gui_Profile.setReport("Bitte gib ein neues Passwort ein.")
self.gui_Profile.e_passwd.focus_set()
elif not len(self.passwd) >= self.passwdMinLength:
self.gui_Profile.setReport("Das neue Passwort muss mindestens " + str(self.passwdMinLength) + " Zeichen enthalten.")
self.gui_Profile.e_passwd.focus_set()
elif self.passwd != self.passwdconfirm:
self.gui_Profile.setReport("Die Passwörter stimmen nicht überein.")
self.gui_Profile.e_passwd2.focus_set()
'''
""" test self.address """
elif self.address == "":
self.gui_Profile.setReport("Bitte gib eine Adresse ein.")
self.gui_Profile.e_address.focus_set()
""" test self.plz only 5 digits """
elif self.plz == "":
self.gui_Profile.setReport("Bitte gib eine Postleitzahl ein.")
self.gui_Profile.e_plz.focus_set()
elif len(self.plz) != 5 or not self.plz.isdigit():
self.gui_Profile.setReport("Die Postleizahl darf nur aus 5 Zahlen bestehen.")
self.gui_Profile.e_plz.focus_set()
""" test self.city """
elif self.city == "":
self.gui_Profile.setReport("Bitte gib einen Wohnort ein.")
self.gui_Profile.e_city.focus_set()
elif not self.city.isalpha() :
self.gui_Profile.setReport("Der Wohnort darf nur Buchstaben enthalten.")
self.gui_Profile.e_city.focus_set()
""" test self.phone """
elif self.phone == "":
self.gui_Profile.setReport("Bitte gib eine Telefonnummer ein.")
self.gui_Profile.e_phone.focus_set()
elif not self.phone.isdigit():
self.gui_Profile.setReport("Die Telefonnummer darf nur Zahlen enthalten.")
self.gui_Profile.e_phone.focus_set()
""" test E-mail """
elif self.email == "":
self.gui_Profile.setReport("Bitte gib eine Email Adresse ein.")
self.gui_Profile.e_email.focus_set()
elif not("@" in self.email) or not("." in self.email):
self.gui_Profile.setReport("Bitte gib eine korrekte Email Adresse ein.")
self.gui_Profile.e_email.focus_set()
else:
self.user.setName(self.name)
self.user.setLastname(self.lastname)
self.user.setUsername(self.username)
self.user.setTel(self.phone)
self.user.setEmail(self.email)
self.user.setStreet(self.address)
self.user.setPlz(self.plz)
self.user.setCity(self.city)
self.gui.getUsers().updateUserXml(self.user)
self.gui_Profile.label_report.config(fg="#25a458")
self.gui_Profile.setReport("Deine Daten wurden erfolgreich geändert.")
def updatePasswd(self, user, oldpasswd, newpasswd, newpasswd2):
print(user.getPasswd())
if oldpasswd== "":
self.gui_Profile.setReport("Bitte geben Sie ihr Passwort ein.")
self.gui_Profile.e_oldpasswd.focus_set()
elif user.getPasswd() != oldpasswd:
self.gui_Profile.setReport("Das eingetragenene Passwort ist nicht korrekt.")
self.gui_Profile.e_oldpasswd.focus_set()
elif newpasswd == "":
self.gui_Profile.setReport("Bitte geben Sie ein neues Passwort ein.")
self.gui_Profile.e_passwd.focus_set()
elif len(newpasswd) < 6:
self.gui_Profile.setReport("Das neue Passwort muss mindestens 6 Buchstaben enthalten.")
self.gui_Profile.e_passwd.focus_set()
elif newpasswd2 == "":
self.gui_Profile.setReport("Bitte geben Sie ein neues Passwort ein.")
self.gui_Profile.e_passwd2.focus_set()
elif(newpasswd!=newpasswd2):
self.gui_Profile.setReport("Die eingetragenen Passwörter stimmen nicht überein.")
self.gui_Profile.e_passwd2.focus_set()
else:
self.user.setPasswd(newpasswd)
self.gui.getUsers().updateUserXml(self.user)
self.gui_Profile.label_report.config(fg="#25a458")
self.gui_Profile.setReport("Das Passwort wurde erfolgreich geändert.")
| Python |
from userList import UserList
class Login():
def __init__(self, root, gui):
self.root = root
self.gui = gui
def checkContent(self, gui_login, username, password):
userMinLength = 6
passwdMinLength = 6
if not (len(username) >= userMinLength):
gui_login.setReport("Der Benutzername muss mindestens "+ str(userMinLength) +" Zeichen lang sein.")
elif not len(password) >= passwdMinLength:
gui_login.setReport("Das Passwort muss mindestens "+ str(passwdMinLength) +" Zeichen lang sein.")
else:
userlist = UserList()
for user in userlist.getUserList():
if (username == user.getUsername()) and (password == user.getPasswd()):
print(user.getUsername())
gui_login.goToGrouplist(user)
else:
gui_login.setReport("Benutzername oder Passwort ist nicht bekannt.")
| Python |
from tkinter import *
from messenger import Messenger
class Gui_Messenger:
def __init__(self, gui):
self.root = Tk()
self.gui = gui
self.messenger = Messenger(self.gui.getUser().getId())
self.root.title("Nachrichten")
self.root.wm_iconbitmap('@'+"campus.xbm")
self.root.geometry("700x700")
self.root.resizable(0,0)
self.main_frame=Frame(self.root, height=650, width=650, bg="#f0f0f0")
self.main_frame.pack( padx=10, pady=10)
self.main_frame.propagate(0)
label_title = Label(self.main_frame, text="Nachrichten:", bg="#f0f0f0", font="bold")
label_title.grid(row=5, column=10)
self.button_top_frame = Frame(self.main_frame, height=30, width=650)
self.button_top_frame.grid(row=10, column=10)
button_inbox = Button(self.button_top_frame, text="Empfangene Nachrichten", command=self.createInboxFrame)
button_inbox.grid(row=10, column=10)
button_outbox = Button(self.button_top_frame, text="Gesendete Nachrichten", command=self.createOutboxFrame)
button_outbox.grid(row=10, column=20)
self.box_frame = Frame(self.main_frame, height=300, width=650)
self.box_frame.grid(row=20, column=10)
self.createInboxFrame()
button_frame = Frame(self.main_frame, height=60, width=250)
button_frame.grid(pady=5, row=30, column=10)
refresh_button = Button(button_frame, text="Neue Nachricht", command=self.writeMessage).grid(row=1, column=1)
show_button = Button(button_frame, text="Nachricht anzeigen" , command=self.showMessage).grid(row=1, column=2)
delete_button = Button(button_frame, text="Nachricht löschen" , command=self.deleteMessage).grid(row=1, column=3)
label_blank = Label(button_frame, text=" ").grid(row=2, column=1)
self.message_frame = Frame(self.main_frame, height=300, width=500, bg="#f0f0f0")
self.message_frame.grid(row=40, column=10)
self.root.mainloop()
def createInboxFrame(self):
self.view = "inbox"
self.box_frame.destroy()
self.box_frame = Frame(self.main_frame, height=300, width=650)
self.box_frame.grid(pady=5, row=20, column=10)
self.listbox = Listbox(self.box_frame, height=10, width=50, font="Verdana", bg="#ffffff")
self.listbox.grid( row = 10, column = 0, sticky= W )
for message in self.messenger.getInboxList():
self.listbox.insert(END, message.show())
self.listbox.activate(0)
scroll = Scrollbar(self.box_frame, command=self.listbox.yview)
self.listbox.configure(yscrollcommand=scroll.set)
scroll.grid(row=10, column=0, sticky=E+N+S)
def createOutboxFrame(self):
self.view = "outbox"
self.box_frame.destroy()
self.box_frame = Frame(self.main_frame, height=300, width=650)
self.box_frame.grid(pady=5, row=20, column=10)
self.listbox = Listbox(self.box_frame, height=10, width=50, font="Verdana", bg="#ffffff")
self.listbox.grid( row = 10, column = 0, sticky= W )
for message in self.messenger.getOutboxList():
self.listbox.insert(END, message.show())
self.listbox.activate(0)
scroll = Scrollbar(self.box_frame, command=self.listbox.yview)
self.listbox.configure(yscrollcommand=scroll.set)
scroll.grid(row=10, column=0, sticky=E+N+S)
def createMessageFrame(self):
self.message_frame.destroy()
self.message_frame = Frame(self.main_frame, height=300, width=500, bg="#f0f0f0")
self.message_frame.grid(row=40, column=10)
def showMessage(self):
self.createMessageFrame();
if (self.view == "inbox"):
for message in self.messenger.getInboxList():
self.Message(message)
else:
for message in self.messenger.getOutboxList():
self.Message(message)
def Message(self, message):
value = self.listbox.get("active")
if value == message.show():
label_message_date = Label(self.message_frame, text=message.getDate(), bg="#ffffff" )
label_message_date.grid( row = 1, column = 1, sticky = W )
label_message_sender = Label(self.message_frame, text=self.gui.getUsers().getUserById(message.getSender()).getName(), bg="#ffffff" )
label_message_sender.grid( row = 1, column = 2, sticky = E )
label_message_subject = Label(self.message_frame, text=message.getSubject(), bg="#ffffff" )
label_message_subject.grid( row = 2, column = 1, sticky = W )
label_message_content = Label(self.message_frame, text=message.getContent(), bg="#ffffff" )
label_message_content.grid( row = 3, column = 1, sticky = W )
def writeMessage(self):
self.createMessageFrame();
label_title = Label(self.message_frame, text="Neue Nachricht erstellen", font="System 14", pady="10")
label_title.grid( row = 1, column = 1, columnspan="2")
label_recipient = Label(self.message_frame, text="Empfänger:")
label_recipient.grid( row = 2, column = 1, sticky = W )
self.input_recipient = Entry(self.message_frame)
self.input_recipient.grid( row = 2, column = 2, sticky = W )
label_subject = Label(self.message_frame, text="Betreff:")
label_subject.grid( row = 3, column = 1, sticky = W )
self.input_subject = Entry(self.message_frame)
self.input_subject.grid( row = 3, column = 2, sticky = W )
label_content = Label(self.message_frame, text="Nachrichtentext:")
label_content.grid( row = 4, column = 1, sticky = W )
self.input_content = Text(self.message_frame,height=10, width=50)
self.input_content.grid( row = 4, column = 2)
send_button = Button(self.message_frame, text="Nachricht senden", command=self.createMessage).grid(row=5, column=1, columnspan="2", pady="10")
def createMessage(self):
self.messenger.writeMessage(self.input_subject.get(), self.input_content.get('0.0',END), self.gui.getUser().getId(), self.input_recipient.get())
self.createOutboxFrame()
self.message_frame.destroy()
def deleteMessage(self):
if (self.view == "inbox"):
for message in self.messenger.getInboxList():
if self.listbox.get("active") == message.show():
print("match")
message.setStatusRecipient("deleted")
self.messenger.updateInboxList()
self.messenger.updateMessage(message)
self.createInboxFrame()
else:
for message in self.messenger.getOutboxList():
if self.listbox.get("active") == message.show():
print("match2")
message.setStatusSender("deleted")
self.messenger.updateOutboxList()
self.messenger.updateMessage(message)
self.createOutboxFrame()
def abbrechen(self):
self.main_frame.destroy()
self.root.destroy()
def setReport(self, text):
self.label_report.config(text=text) | Python |
class WallMessage:
def createMessage(self, sender, date, content):
self.sender = sender
self.date = date
self.content = content
def getSender(self):
return self.sender
def getDate(self):
return self.date
def getContent(self):
return self.content
def getTime(self):
return self.time
def editMessage(self, subject, content):
self.subject = subject
self.content = content
# date definieren
| Python |
class User:
def __init__(self):
self.groupList = []
def createXmlUser(self, userid, name, lastname, username, passwd, phone, email, address, plz, city):
self.userid = userid
self.name = name
self.lastname = lastname
self.username = username
self.passwd = passwd
self.phone = phone
self.email = email
self.address = address
self.plz = plz
self.city = city
def displayUser(self):
print ("Name : ", self.userid, self.name, self.lastname, self.username, self.passwd, self.phone, self.email, self.address, self.plz, self.city )
def getId(self):
return self.userid
def getName(self):
return self.name
def getLastname(self):
return self.lastname
def getUsername(self):
return self.username
def getPasswd(self):
return self.passwd
def getPhone(self):
return self.phone
def getTel(self):
return self.phone
def getEmail(self):
return self.email
def getAddress(self):
return self.address
def getStreet(self):
return self.address
def getPlz(self):
return self.plz
def getCity(self):
return self.city
def getGroupList(self):
return self.groupList
def setId(self, userid):
self.userid = userid
def setName(self, name):
self.name = name
def setLastname(self, lastname):
self.lastname = lastname
def setUsername(self, username):
self.username = username
def setPasswd(self, passwd):
self.passwd = passwd
def setTel(self, phone):
self.phone = phone
def setEmail(self, email):
self.email = email
def setStreet(self, address):
self.address = address
def setPlz(self, plz):
self.plz = plz
def setCity(self, city):
self.city = city
def addGroup(self, group):
self.groupList.append(group)
def getGroups(self):
for group in self.groupList:
print(group)
#def saveUser(self, userid, name, lastname, username, passwd, plz, status, group):
# person = ET.Element('personen')
# root.append(person)
# wrap it in an ElementTree instance, and save as XML
#tree = ET.ElementTree(root)
#tree.write("Personen.xml") | Python |
sql_statement = ""
with open('clientes.tsv') as f:
i = 0
for line in f:
client = line.rstrip('\n').split('\t')
barrio = ""
if client[1] == '""':
barrio = 'ZARAGOCILLA'
else:
barrio = client[1]
sql_statement += 'INSERT INTO "MaeCliente" ("usuarioGrab", "usuarioUltMod", "activo", "codMaeCliente", "codMaeBarrio", "nombreMaeCliente", "telefono", "direccion", "eMail", "tagFiltro")\n'
sql_statement += "VALUES ('ADMIN', 'ADMIN', TRUE, '" + client[0] + "', '" + barrio + "', '" + client[2] + "', '" + client[3] + "', '" + client[4] + "', '" + client[5] + "', coalesce('" + client[0] + "','') || ' - ' || coalesce('" + client[2] + "',''));\n\n"
with open('insertar_maestros_clientes.sql', 'w') as f:
f.write(sql_statement)
| Python |
sql_statement = ""
with open('barrios_cartagena.txt') as f:
for line in f:
line_no_newline = line.rstrip('\n')
sql_statement += 'INSERT INTO "MaeBarrio" ("usuarioGrab", "usuarioUltMod", "activo", "codMaeBarrio", "codMaeCiudad", "nombreMaeBarrio", "localidad")\n'
sql_statement += "VALUES('ADMIN', 'ADMIN', TRUE, '" + line_no_newline + "', 'Cartagena', '" + line_no_newline + "', '');\n\n"
with open('insertar_maestros_barrios.sql', 'w') as f:
f.write(sql_statement)
| Python |
import numpy as np
import time
import scipy
import scipy.sparse as ss
import scipy.sparse.linalg as linalg
def solve_k_coo_sub(model):
full_displ = {}
full_F = {}
for sub in model.subcases.values():
#
F = model.F[sub.id]
#
K = model.k_coo_sub[sub.id]
#
x = linalg.spsolve( K.tocsc(), F )
#
index_to_zero = model.index_to_delete[sub.id]
#for i in index_to_zero:
# if i > len(x):
# i = len(x)
# x = scipy.insert( x , i , 0. )
full_displ[sub.id] = x
full_F[sub.id] = np.dot( model.k_coo, x )
return [full_displ, full_F]
| Python |
from solver import *
| Python |
from abaqus import *
from abaqusConstants import *
from regionToolset import Region
def model_create( mdb, model ):
mdb.Model( model.name)
class AModel(object):
def __init__( self ):
self.amodel = amodel
print 'CYLINDER MODULE'
backwardCompatibility.setValues(includeDeprecated=True, reportDeprecated=False)
mdb.saveAs(pathName='C:/Temp/abaqus/cylinder.cae')
#RESETING THE CURRENT VIEWPORT
myView = session.viewports[ session.currentViewportName ]
myView.setValues( displayedObject=None )
#CREATING A NEW MODEL
myMod = mdb.Model(name=MODELNAME)
#DELETING THE DEFAULT MODEL
#del mdb.models['Model-1']
#CREATING A NEW PART
partCyl = myMod.Part( name='Cylinder',
dimensionality=THREE_D,
type=DEFORMABLE_BODY )
#CREATING AN ISOTROPIC MATERIAL
myMat = myMod.Material( name='aluminum' )
elasticProp = ( E, NU )
myMat.Elastic( table=( elasticProp , ) )
#CREATING THE PROPERTY (isotropic shell)
shellSection = myMod.HomogeneousShellSection( name='AluminumPlate',
material='aluminum',
thickness=T )
#CREATING THE SKETCH which will be used to create the shell geometry
s1 = myMod.ConstrainedSketch( name='SketchCylinder',
sheetSize=max( [2.1*R, 1.1*H] ) )
#axis of revolution
s1.ConstructionLine( point1=(0,-H), point2=(0,H) )
#line to be revoluted
s1.Line( point1=(R,-H/2.), point2=(R,H/2.) )
#CREATING A LOCAL COORDINATE SYSTEM TO USE IN THE BOUNDARY CONDITIONS
csysCyl = partCyl.DatumCsysByThreePoints( name='CSYSCylinder',
coordSysType=CYLINDRICAL,
origin=(0,0,0),
point1=(1,0,0),
point2=(1,0,-1) )
#CREATING THE CYLINDER SHELL GEOMETRY
myCyl = partCyl.BaseShellRevolve( sketch=s1,
angle=360.0,
flipRevolveDirection=OFF )
#PROPERTY - assigning the property to the corresponding faces
partCyl.SectionAssignment(
region=Region( faces=partCyl.faces.findAt(((-R,0,0),)) ),
sectionName='AluminumPlate' )
#DEFINING THE MESH SEEDS ALONG ALL EDGES
partCyl.PartitionEdgeByParam( edges=partCyl.edges.findAt( ((R,0,0),) ),
parameter=PLpoint )
partCyl.seedEdgeBySize(edges= partCyl.edges.findAt( ((R,-H/2,0),) ),
size=ELSIZE,
deviationFactor=0.1,
constraint=FINER)
partCyl.seedEdgeBySize(edges= partCyl.edges.findAt( ((R, H/2,0),) ),
size=ELSIZE,
deviationFactor=0.1,
constraint=FINER)
partCyl.seedEdgeBySize(edges= partCyl.edges.findAt( ((R,-H/4,0),) ),
size=ELSIZE,
deviationFactor=0.1,
constraint=FINER)
partCyl.seedEdgeBySize(edges= partCyl.edges.findAt( ((R, H/4,0),) ),
size=ELSIZE,
deviationFactor=0.1,
constraint=FINER)
#ASSEMBLIES adding the cylinder to assembly
instCyl = myMod.rootAssembly.Instance( name='InstanceCylinder',
part=partCyl,
dependent=ON)
#BOUNDARY CONDITIONS
localCSYS = instCyl.datums[1]
#bot boundary conditions
botEdgeArray = instCyl.edges.findAt( ( (-R,-H/2,0 ), ) )
myMod.DisplacementBC( name='BotBC',
createStepName='Initial',
region = Region( edges=botEdgeArray ),
u1=UNSET,
u2=SET,
u3=SET,
ur1=SET,
ur2=UNSET,
ur3=UNSET,
amplitude = UNSET,
distributionType = UNIFORM,
fieldName = '',
localCsys = localCSYS,
#buckleCase=BUCKLING_MODES
) #NOT_APPLICABLE
#top boundary conditions
topEdgeArray = instCyl.edges.findAt( ( (-R, H/2,0 ), ) )
myMod.DisplacementBC( name='TopBC',
createStepName='Initial',
region = Region( edges=topEdgeArray ),
u1=UNSET,
u2=SET,
u3=UNSET,
ur1=SET,
ur2=UNSET,
ur3=UNSET,
amplitude = UNSET,
distributionType = UNIFORM,
fieldName = '',
localCsys = localCSYS,
#buckleCase=BUCKLING_MODES
) #NOT_APPLICABLE
#LOADS
myMod.StaticStep( name='PerturbationStep',
previous='Initial',
nlgeom=True )
#perturbation load
verticePL = instCyl.vertices.findAt( ((R, 0, 0),) )
myMod.ConcentratedForce( name='PerturbationLoad',
createStepName = 'PerturbationStep',
region= Region( vertices=verticePL ),
cf1 = -PLVALUE,
cf2 = 0.,
cf3 = 0. )
#axial load
topEdgeArray = instCyl.edges.findAt( ( (-R, H/2,0 ), ) )
myMod.ShellEdgeLoad(name='Load-3',
createStepName='PerturbationStep',
region=Region( side1Edges=topEdgeArray ),
magnitude=AXIALLOAD,
directionVector=((0.0, 0.0, 0.0), (0.0, -1.0, 0.0)),
distributionType=UNIFORM,
field='',
localCsys=None,
traction=GENERAL,
follower=OFF)
#MESHING THE PART
partCyl.generateMesh()
#CREATING JOB
job = mdb.Job( name =JOBNAME,
model = myMod,
scratch = r'c:\Temp\abaqus\scratch',
memory = 4,
memoryUnits = GIGA_BYTES,
#numCpus = 6,
)
job.writeInput(consistencyChecking=OFF)
mdb.save()
#: The model database has been saved to "C:\Temp\abaqus\test2.cae".
if __name__ == '__main__':
R = 50.
H = 200.
T = 2.
E = 71e3
NU = 0.33
ELSIZE = 2.
PLVALUE = 100.
PLpoint = 0.5 #cylinder height ratio
AXIALLOAD = 1000.
for i in range(10):
PLpoint = 0.05 + 0.1*i
JOBNAME = 'myJob_' + str(i)
MODELNAME = 'Cylinder Model ' + str(i)
isoCylinder( R, H, T, E, NU,
ELSIZE, PLVALUE, PLpoint, AXIALLOAD, JOBNAME, MODELNAME)
| Python |
import abaqus
| Python |
import numpy as np
from alg3dpy.constants import *
from mapy.model.coords import CoordR
vecxz = Vec( np.array((1,0,1), dtype=FLOAT) )
CSYSGLOBAL = CoordR(0, O, None, Z, vecxz )
CSYSGLOBAL.rebuild( rcobj = None, force_new_axis = False )
CSYSGLOBAL.rcobj = CSYSGLOBAL
| Python |
import os
from cardtranslator import *
from input_reader import *
def user_setattr(obj, inputs):
for k,v in inputs.iteritems():
if k.find('blank') > -1:
continue
#FIXME I removed this if below...
#if getattr(obj, k, False) == False:
str_test = str( v )
if str_test.find('.') > -1 and str_test.find('mapy.') == -1:
try:
setattr(obj, k, float( v ) )
except:
print 'Exception in mapy.reader.user_setattr...'
print 'str_test is ', str_test
print 'v is ', v
setattr(obj, k, v )
elif k.find('id') > -1:
if v == None or v == '':
setattr(obj, k, v )
else:
setattr(obj, k, int( v ))
else:
setattr(obj, k, v )
#the if was finishing here before alteration
return obj
| Python |
import mapy
from mapy.reader import *
from mapy.model import *
def card2dict(inputcard, inputsolvername, outputsolvername = 'generic'):
"""
Returns a tranlated output card, given the solver name and inputcard.
If no output solver name is given the 'generic' one is used as default.
"""
outputcard={}
cardname = inputcard['card']
trans = translator( inputsolvername )[1]
outputcard['entryclass'] = trans[ cardname ]['entryclass']
for oldkey in inputcard.keys():
if oldkey.find('blank') > -1: continue
newkey = trans[cardname][oldkey]
outputcard[newkey] = inputcard[oldkey]
if outputsolvername <> 'generic':
inputcard = outputcard
outputcard = {}
cards = translator(outputsolvername)[0]
trans = translator(outputsolvername)[1]
for entry in cards[cardname]:
if entry.find('blank') > -1:
outputcard[entry] = entry
continue
outputcard[entry]=inputcard[trans[cardname][entry]]
return outputcard
def translator(solvername):
"""
Returns all configured cards and tranlator dictionary for a given
solver name.
"""
if solvername.lower()=='nastran':
cards={
'CORD1R':['card','cida','g1a','g2a','g3a','cidb','g1b','g2b','g3b'],
'CORD2R':['card','cid','rid','a1','a2','a3','b1','b2','b3','blank1',
'blank2','c1','c2','c3'],
'CORD1C':['card','cida','g1a','g2a','g3a','cidb','g1b','g2b','g3b'],
'CORD2C':['card','cid','rid','a1','a2','a3','b1','b2','b3','blank1',
'blank2','c1','c2','c3'],
'CORD1S':['card','cida','g1a','g2a','g3a','cidb','g1b','g2b','g3b'],
'CORD2S':['card','cid','rid','a1','a2','a3','b1','b2','b3','blank1',
'blank2','c1','c2','c3'],
'GRID':['card','id','cp','x1','x2','x3','cd','ps','seid'],
'MAT1':['card','mid','e','g','nu','rho','a','tref','ge','blank1',
'blank2','st','sc','ss','mcsid'],
'MAT8':['card','mid','e1','e2','nu12','g12','g1z','g2z','rho','blank1',
'blank2','a1','a2','tref','xt','xc','yt','yc','s','blank3',
'blank4','ge','f12','strn'],
'PROD':['card','pid','mid','a','j','c','nsm'],
'CROD':['card','eid','pid','g1','g2'],
'PBAR':['card','pid','mid','a','i1','i2','j','nsm','blank1',
'blank2','blank3','c1','c2','d1','d2','e1','e2','f1','f2',
'blank3','blank4','k1','k2','i12'],
'CBAR':['card','eid','pid','ga','gb','x1','x2','x3','offt',
'blank1','blank2','pa','pb','w1a','w2a','w3a',
'w1b','w2b','w3b'],
'PCOMP':['card','pid','z0','nsm','sb','ft','tref','ge','lam',
'blank1', 'blank2','mid___list___2___4', 't___list___3___4',
'theta___list___4___4'],
'LOAD':['card','sid','s', 'scales___list___4___2',
'loads___list___5___2'],
'PSHELL':['card','pid','mid1','t','mid2','12i/t**3','mid3','ts/t',
'nsm','blank1','blank2','z1','z2','mid4'],
'CTRIA3':['card','eid','pid','g1','g2','g3','theta_or_mcid',
'zoffs'],
'CQUAD4':['card','eid','pid','g1','g2','g3','g4','theta_or_mcid',
'zoffs'],
'FORCE':['card','sid', 'g', 'cid', 'f', 'n1', 'n2', 'n3'],
'FORCE1':['card','sid', 'g', 'f', 'g1', 'g2'],
'MOMENT':['card','sid', 'g', 'cid', 'f', 'n1', 'n2', 'n3'],
'SPC':['card','sid', 'g1', 'c1', 'd1', 'g2', 'c2', 'd2']
}
trans_out={
'CORD1R':{'entryclass':mapy.model.coords.CoordR, 'card':'card',
'cida':'ida', 'g1a':'g1a' ,'g2a':'g2a', 'g3a':'g3a',
'cidb':'idb', 'g1b':'g1b', 'g2b':'g2b', 'g3b':'g3b'},
'CORD2R':{'entryclass':mapy.model.coords.CoordR, 'card':'card',
'cid':'id', 'rid':'rcid',
'a1':'a1', 'a2':'a2', 'a3':'a3',
'b1':'b1', 'b2':'b2', 'b3':'b3',
'c1':'c1', 'c2':'c2', 'c3':'c3'},
'CORD1C':{'entryclass':mapy.model.coords.CoordC, 'card':'card',
'cida':'ida', 'g1a':'g1a' ,'g2a':'g2a', 'g3a':'g3a',
'cidb':'idb', 'g1b':'g1b', 'g2b':'g2b', 'g3b':'g3b'},
'CORD2C':{'entryclass':mapy.model.coords.CoordC, 'card':'card',
'cid':'id', 'rid':'rcid',
'a1':'a1', 'a2':'a2', 'a3':'a3',
'b1':'b1', 'b2':'b2', 'b3':'b3',
'c1':'c1', 'c2':'c2', 'c3':'c3'},
'CORD1S':{'entryclass':mapy.model.coords.CoordS, 'card':'card',
'cida':'ida', 'g1a':'g1a' ,'g2a':'g2a', 'g3a':'g3a',
'cidb':'idb', 'g1b':'g1b', 'g2b':'g2b', 'g3b':'g3b'},
'CORD2S':{'entryclass':mapy.model.coords.CoordS, 'card':'card',
'cid':'id', 'rid':'rcid',
'a1':'a1', 'a2':'a2', 'a3':'a3',
'b1':'b1', 'b2':'b2', 'b3':'b3',
'c1':'c1', 'c2':'c2', 'c3':'c3'},
'GRID':{'entryclass':mapy.model.grids.Grid, 'card':'card', 'id':'id',
'cp':'rcid', 'x1':'x1' ,'x2':'x2', 'x3':'x3',
'cd':'ocid', 'ps':'perm_cons', 'seid':'seid'},
'MAT1':{'entryclass':mapy.model.materials.matiso.MatIso,
'card':'card', 'mid':'id', 'e':'e', 'g':'g', 'nu':'nu',
'rho':'rho', 'a':'a', 'tref':'tref',
'ge':'damp', 'st':'st', 'sc':'sc', 'ss':'ss',
'mcsid':'mcsid'},
'MAT8':{'entryclass':mapy.model.materials.matiso.MatLamina,
'card':'card', 'mid':'id', 'e1':'e1', 'e2':'e2', 'nu12':'nu12',
'g12':'g12', 'g1z':'g13', 'g2z':'g23', 'rho':'rho',
'a1':'a1', 'a2':'a2', 'a3':'a3', 'tref':'tref',
'xt':'st1', 'xc':'sc1', 'yt':'st2', 'yc':'sc2', 's':'ss12',
'ge':'damp', 'f12':'NOT', 'strn':'strn' },
'PROD':{'entryclass':mapy.model.properties.prop1d.PropRod,
'card':'card', 'pid':'id', 'mid':'mid', 'a':'a', 'j':'j',
'c':'c', 'nsm':'nsm'},
'CROD':{'entryclass':mapy.model.elements.elem1d.ElemRod,
'card':'card', 'eid':'id', 'pid':'pid', 'g1':'g1', 'g2':'g2'},
'PBAR':{'entryclass':mapy.model.properties.prop1d.PropBar,
'card':'card', 'pid':'id', 'mid':'mid', 'a':'a', 'i1':'i1',
'i2':'i2', 'i12':'i12', 'j':'j', 'nsm':'nsm', 'c1':'a1',
'd1':'a2', 'e1':'a3', 'f1':'a4', 'c2':'b1', 'd2':'b2',
'e2':'b3', 'f2':'b4', 'k1':'ka', 'k2':'kb'},
'CBAR':{'entryclass':mapy.model.elements.elem1d.ElemBar,
'card':'card', 'eid':'id', 'pid':'pid', 'ga':'g1', 'gb':'g2',
'x1':'x1', 'x2':'x2', 'x3':'x3', 'offt':'offt','pa':'pa',
'pb':'pb', 'w1a':'w1a', 'w2a':'w2a', 'w3a':'w3a', 'w1b':'w1b',
'w2b':'w2b', 'w3b':'w3b'},
'PCOMP':{'entryclass':mapy.model.properties.prop2d.PropShellComp,
'card':'card', 'pid':'id', 'z0':'z0',
'nsm':'nsm', 'sb':'sbmat', 'ft':'ft',
'tref':'tref', 'ge':'dampc', 'lam':'lam',
'mid___list___2___4':'midlist', 't___list___3___4':'tlist',
'theta___list___4___4':'thetalist'},
'LOAD':{'entryclass':mapy.model.loads.Load, 'card':'card',
'sid':'id', 's':'scale_overall',
'scales___list___4___2':'scales',
'loads___list___5___2':'loads'},
'PSHELL':{'entryclass':mapy.model.properties.prop2d.PropShell,
'card':'card', 'pid':'id', 'mid1':'mid', 't':'t',
'mid2':'mid2', '12i/t**3':'12i/t**3', 'mid3':'mid3',
'ts/t':'ts/t', 'nsm':'nsm', 'z1':'fiberdistbot',
'z2':'fiberdisttop'},
'CTRIA3':{'entryclass':mapy.model.elements.elem2d.ElemTria3,
'card':'card', 'eid':'id', 'pid':'pid', 'g1':'g1', 'g2':'g2',
'g3':'g3', 'theta_or_mcid':'theta_or_mcid', 'zoffs':'zoffs'},
'CQUAD4':{'entryclass':mapy.model.elements.elem2d.ElemQuad4,
'card':'card', 'eid':'id', 'pid':'pid', 'g1':'g1', 'g2':'g2',
'g3':'g3', 'g4':'g4', 'theta_or_mcid':'theta_or_mcid',
'zoffs':'zoffs'},
'FORCE':{'entryclass':mapy.model.loads.Force, 'card':'card',
'sid':'id', 'g':'gridid', 'cid':'cid', 'f':'f', 'n1':'x1',
'n2':'x2', 'n3':'x3'},
'FORCE1':{'entryclass':mapy.model.loads.Force, 'card':'card',
'sid':'id', 'g':'gridid', 'f':'f', 'g1id':'g1id',
'g2id':'g2id'},
'MOMENT':{'entryclass':mapy.model.loads.Moment, 'card':'card',
'sid':'id', 'g':'gridid', 'cid':'cid', 'f':'f', 'n1':'x1',
'n2':'x2', 'n3':'x3'},\
'SPC':{'entryclass':mapy.model.constraints.SPC, 'card':'card',
'sid':'id', 'g1':'gridid', 'c1':'dof', 'd1':'displ',
'g2':'g2', 'c2':'c2', 'd2':'d2' }
}
return [cards, trans_out]
| Python |
import mapy
from mapy.reader import *
global tempcard
def addfield(tempcard, field, value):
found = False
field = float(field)
field += 1
for k in tempcard.keys():
if k.find('___') > -1:
entrynum = float(k.split('___')[2])
step = float(k.split('___')[3])
found = False
if (field - entrynum)/step == 0 or (field - entrynum)/step == 1:
found = True
tempcard[k].append(value)
break
def fieldsnum(line):
if line.find(',') == -1:
line = line.split('\n')[0]
num = len(line)/8
# the operator below gived the rest of the division
if len(line) % 8. > 0.:
num = num + 1
else:
num = len(line.split(','))
return num
class InputFile:
"""
Input file containing a FEM model bulk
"""
def __init__(self, abspath, solvername='nastran'):
self.abspath = abspath
self.solvername = solvername
list_cards_translator = translator( self.solvername )
self.cards = list_cards_translator[0]
self.translator = list_cards_translator[1]
self.readfile()
self.createdata()
self.memorycleanup()
def readfile(self):
if os.path.isfile(self.abspath):
datfile = open(self.abspath, 'r')
else:
raise 'Input file : %s was not found!' % self.abspath
self.lines = datfile.readlines()
datfile.close()
def memorycleanup(self):
self.lines = None
def createdata(self):
#
self.data = []
#
for i in range(len(self.lines)):
line = self.lines[i]
if line.strip()[0] == '$':
continue
if line.find(',') > -1:
numfields = fieldsnum(line)
fields = [i.strip() for i in line.split(',')]
else:
numfields = fieldsnum(line)
fields = [line[(0 + i * 8):(8 + i * 8)].strip()\
for i in range(numfields)]
if (fields[0].find('+') > -1 or fields[0] == '' or \
fields[0] == ' ') and validentry == True:
countentry += 1
elif fields[0] in self.cards:
validentry = True
countentry = 0
currcard = fields[0]
cardfieldsnum = len(self.cards[currcard])
try:
if len(tempcard) > 0:
self.data.append(tempcard)
except NameError:
pass
tempcard = {}
listentries = None
else:
validentry = False
countentry = 0
if validentry == True or countentry > 0:
blanknum = 10 - numfields
for field_i in range(numfields):
field_j = field_i + 10 * countentry
fieldvalue = fields[field_i]
if (field_j + 1) <= cardfieldsnum:
fieldname = self.cards[currcard][field_j]
if fieldname.find('___') > -1:
tempcard[fieldname] = [fieldvalue]
else:
tempcard[fieldname] = fieldvalue
else:
addfield(tempcard, field_i, fieldvalue)
#FIXME the for below was commented because it aimed to blank the
#fields... they are simply ignored in the
#mapy.reader.user_setattr method, using the given 'blank' flag
#for blank_field_i in range(blanknum):
# tmp = blank_field_i + numfields
# if (tmp + 1) <= cardfieldsnum:
# tempcard[self.cards[currcard][tmp]] = ''
try:
if len(tempcard) > 0:
self.data.append(tempcard)
except NameError:
pass
| Python |
import mapy
from mapy import FEM
from vtk import *
from random import random
def randomrgb():
r = random() * 255
g = random() * 255
b = random() * 255
return [r, g, b]
class FEMView(FEM):
def __init__(self, model):
FEM.__init__(self)
self.points = vtkPoints()
x1min = 1000000.
x2min = 1000000.
x3min = 1000000.
x1max = 0.000001
x2max = 0.000001
x3max = 0.000001
for grid in model.griddict.values():
x1 = float(grid.x1)
x2 = float(grid.x2)
x3 = float(grid.x3)
if x1 < x1min: x1min = x1
if x2 < x2min: x2min = x2
if x3 < x3min: x3min = x3
if x1 > x1max: x1max = x1
if x2 > x2max: x2max = x2
if x3 > x3max: x3max = x3
self.points.InsertPoint(grid.id, x1, x2, x3)
self.quads = {}
self.triangles = {}
self.lines = {}
for elem in model.elemdict.values():
if elem.mask == True: continue
if elem.entryclass.find('ElemQuad') > -1:
self.quads[elem.id] = vtkQuad()
fvelem = self.quads[elem.id]
elif elem.entryclass.find('ElemTria') > -1:
self.triangles[elem.id] = vtkTriangle()
fvelem = self.triangles[elem.id]
elif elem.entryclass.find('ElemRod') > -1:
self.lines[elem.id] = vtkLine()
fvelem = self.lines[elem.id]
for i in range(len(elem.grids)):
grid = elem.grids[i]
fvelem.GetPointIds().SetId(i, grid.id)
# creating actors for each model property
self.elemArrays = {}
self.elemPolyDatas = {}
self.dataMappers = {}
self.actors = {}
self.vtkprops = {}
for prop in model.propdict.values():
self.elemArrays[prop.id] = vtkCellArray()
self.elemPolyDatas[prop.id] = vtkPolyData()
self.dataMappers[prop.id] = vtkPolyDataMapper()
self.actors[prop.id] = vtkActor()
self.vtkprops[prop.id] = vtkProperty()
elemArray = self.elemArrays[prop.id]
elemPolyData = self.elemPolyDatas[prop.id]
dataMapper = self.dataMappers[prop.id]
actor = self.actors[prop.id]
vtkprop = self.vtkprops[prop.id]
for k in self.quads.keys():
quad = self.quads[k]
if model.elemdict[k].pobj.id == prop.id:
elemArray.InsertNextCell(quad)
for tria in self.triangles.values():
if tria.prop.id == prop.id:
elemArray.InsertNextCell(tria)
elemPolyData.SetPoints(self.points)
elemPolyData.SetPolys(elemArray)
dataMapper.SetInput(elemPolyData)
actor.SetMapper(dataMapper)
rgb = randomrgb()
vtkprop.SetColor(rgb)
vtkprop.LightingOn()
vtkprop.SetInterpolationToFlat()
vtkprop.SetRepresentationToSurface()
actor.SetProperty(vtkprop)
self.render()
def render(self):
self.ren = vtkRenderer()
for actor in self.actors.values():
self.ren.AddActor(actor)
#self.ren.SetBackground(util.colors.slate_grey)
self.renwin = vtkRenderWindow()
self.renwin.AddRenderer(self.ren)
self.renwin.SetSize(500, 500)
style = vtkInteractorStyleTrackballCamera()
self.iren = vtkRenderWindowInteractor()
self.iren.SetInteractorStyle(style)
self.iren.SetRenderWindow(self.renwin)
self.iren.Initialize()
self.renwin.Render()
self.iren.Start()
self.renwin.Finalize()
def close(self):
self.renwin.Finalize()
| Python |
import os
#import solver
class FEM(object):
'''
Finite Element Method class
'''
def __init__(self):
pass
def create_model(self, name='default_name'):
self.model = model.Model( name )
def read_new_file(self, file_path, solvername='nastran'):
solvername = solvername.lower()
self.file = reader.InputFile(file_path, solvername)
model_name = os.path.basename(file_path)
self.create_model(model_name)
for data in self.file.data:
outputcard = reader.card2dict(data, self.file.solvername)
obj = outputcard['entryclass'](outputcard)
obj.entryclass = str(obj.entryclass)
obj.add2model(self.model)
def solve_k_coo_sub(self):
[full_displ, full_F] = solver.solve_k_coo_sub(self.model)
ind = 0
for gid in self.model.k_pos:
grid = self.model.griddict[gid]
for sub in self.model.subcases.values():
displ = full_displ[sub.id][ind*6 : ind*6 + 6]
grid.attach_displ( sub.id, displ )
ind += 1
import model
import reader
import constants
| Python |
import numpy as np
#FIXME build the K matrix using Gauss-Legendre numerical integration
#
import alg3dpy
from mapy.model.elements.elem2d import Elem2D
from mapy.reader import user_setattr
class ElemTria3(Elem2D):
def __init__(self, inputs):
Elem2D.__init__(self)
self = user_setattr(self, inputs)
def rebuild(self):
Elem2D.rebuild(self)
#self.build_kelem()
def build_kelem(self):
import scipy
C = self.pobj.C
t = self.pobj.t
#global coords
x1, x2, x3 = self.grids[0].x1 , self.grids[1].x1 , self.grids[2].x1
y1, y2, y3 = self.grids[0].x2 , self.grids[1].x2 , self.grids[2].x2
z1, z2, z3 = self.grids[0].x3 , self.grids[1].x3 , self.grids[2].x3
#loading coords relative to element plane
global_coords = scipy.array([\
[x1, x2, x3],\
[y1, y2, y3],\
[z1, z2, z3]], dtype='float32')
local_coords = np.dot( self.Rcoord2el, global_coords )
x1, x2, x3 = local_coords[0]
y1, y2, y3 = local_coords[1]
area = alg3dpy.area_tria( self.grids[0], self.grids[1], self.grids[2] )
J = 2. * area
L1x = y2 - y3
L1y = x3 - x2
L2x = y3 - y1
L2y = x1 - x3
L3x = y1 - y2
L3y = x2 - x1
#membrane terms
B = (1/(2.*area)) * scipy.array(\
[[ L1x,0,0,0,0,0, L2x,0,0,0,0,0, L3x,0,0,0,0,0],
[ 0,L1y,0,0,0,0, 0,L2y,0,0,0,0, 0,L3y,0,0,0,0],
[L1y,L1x,0,0,0,0, L2y,L2x,0,0,0,0, L3y,L3x,0,0,0,0]])
B_T = B.transpose()
self.kelem = t*area* np.dot( np.dot( B_T, C ), B )*J
#bending terms
| Python |
from elemtria3 import *
| Python |
import sympy
from sympy.core.power import Pow
import sys
from sympy.matrices import Matrix
sympy.var('x y x1 y1 x2 y2 x3 y3 z z1 z2 z3 area')
def area_tria(x1,x2,x3,y1,y2,y3,z1,z2,z3):
a = sympy.sqrt(Pow(x2-x1,2) + Pow(y2-y1,2) + Pow(z2-z1,2))
b = sympy.sqrt(Pow(x3-x1,2) + Pow(y3-y1,2) + Pow(z3-z1,2))
c = sympy.sqrt(Pow(x3-x2,2) + Pow(y3-y2,2) + Pow(z3-z2,2))
p = (a + b + c)/2.
return sympy.sqrt( p*(p-a)*(p-b)*(p-c) )
L2 = area_tria(x,x1,x3,y,y1,y3,z,z1,z3)
L3 = area_tria(x,x2,x3,y,y2,y3,z,z2,z3) / area
print 'L2 =',L2
print 'L3 =',L3
sympy.pprint(L2)
print sys.argv
| Python |
import alg3dpy
from mapy.model.elements.elem1d import Elem1D
from mapy.reader import user_setattr
#
class ElemBar(Elem1D):
def __init__(self, inputs):
Elem1D.__init__(self)
self = user_setattr(self, inputs)
def rebuild(self):
Elem1D.rebuild(self)
self.calc_ovec()
self.calc_vecs()
self.calc_Rmatrix()
self.build_kelem()
def calc_ovec(self):
if self.x2 == '' or self.x3 == '':
gref = self.model.griddict[int(self.x1)]
self.ovec = alg3dpy.Vec([(gref.x1 - self.grids[0].x1), \
(gref.x2 - self.grids[0].x2), \
(gref.x3 - self.grids[0].x3)])
else:
self.ovec = alg3dpy.Vec(self.x1, self.x2, self.x3)
def test_build_kelem(self):
return
#
#FIXME these k below are valid for rectangular sections only
x1 = 0.
x2 = self.L
A = self.pobj.a
C = self.pobj.C
E = self.pobj.matobj.e
G = self.pobj.G
Izz = self.pobj.i1
Iyy = self.pobj.i2
#truss terms
kelem = scipy.ones((12,12))
#FIXME change this pts... take from the gauss_legendre.py module
pts = [0.]
for r in pts:
h1 = (1-r)/2.
h1r = -1/2.
h2 = (1+r)/2.
h2r = 1/2.
J = x2/2. #h1r*x1 + h2r*x2
#truss
Bi = 1./J * scipy.array([\
[ h1r,0,0,0,0,0, h2r,0,0,0,0,0 ], #ex
[ 0,0,0,0,0,0, 0,0,0,0,0,0 ], #betaxy
[ 0,0,0,0,0,0, 0,0,0,0,0,0 ]]) #betaxz
kelem += np.dot( np.dot( Bi.transpose(), C ), Bi )*J
#XY components
# Hw = scipy.array([[ 0,0,0,0,0,0, 0,0,0,0,0,0 ],
# [ 0,h1,0,0,0,0, 0,h2,0,0,0,0 ],
# [ 0,0,0,0,0,0, 0,0,0,0,0,0 ]])
Bi = 1./J * scipy.array([[ h1r,0,0,0,0,0, h2r,0,0,0,0,0 ],
[ 0,h1r,0,0,0,-h1, 0,h2r,0,0,0,-h2 ],
[ 0,0,h1r,0,h1,0, 0,0,0,0,h2,0 ]])
# Hb = scipy.array([[ 0,0,0,0,0,0, 0,0,0,0,0,0 ],
# [ 0,0,0,0,0,h1, 0,0,0,0,0,h2 ],
# [ 0,0,0,0,0,0, 0,0,0,0,0,0 ]])
kelem += E*Izz* np.dot( Bi.transpose(), Bi )*J
# #XZ component
# Hw = scipy.array([[ 0,0,0,0,0,0, 0,0,0,0,0,0 ],
# [ 0,0,0,0,0,0, 0,0,0,0,0,0 ],
# [ 0,0,h1,0,0,0, 0,0,h2,0,0,0 ]])
# Bw = 1./J * scipy.array([[ 0,0,0,0,0,0, 0,0,0,0,0,0 ],
# [ 0,0,0,0,0,0, 0,0,0,0,0,0 ],
# [ 0,0,h1r,0,0,0, 0,0,h2r,0,0,0 ]])
# Hb = scipy.array([[ 0,0,0,0,0,0, 0,0,0,0,0,0 ],
# [ 0,0,0,0,0,0, 0,0,0,0,0,0 ],
# [ 0,0,0,0,h1,0, 0,0,0,0,h2,0 ]])
# Bb = 1./J * scipy.array([[ 0,0,0,0,0,0, 0,0,0,0,0,0 ],
# [ 0,0,0,0,0,0, 0,0,0,0,0,0 ],
# [ 0,0,0,0,h1r,0, 0,0,0,0,h2r,0 ]])
# kelem += E*Iyy*np.dot( Bb.transpose(), Bb )*J
print 'E',E
print 'G',G
print 'Izz',Izz
print 'Iyy',Iyy
self.kelem = kelem * 2.
def build_kelem(self):
import scipy
import scipy.sparse as ss
A = self.A
E = self.E
L = self.L
#truss terms
data1 = scipy.array([E*A/L,-E*A/L,-E*A/L,E*A/L])
row1 = scipy.array([ 0, 6, 0, 6])
col1 = scipy.array([ 0, 0, 6, 6])
#bending in plane XY terms
EI_L = E*self.Izz/self.L
k1 = 12*EI_L/L**2
k2 = 6*EI_L/L
k3 = 4*EI_L
k4 = 2*EI_L
data2 = [k1, k2,-k1,k2,k3,-k2,k4,k1,-k2,k3,k2,-k1,-k2,k2,k4,-k2]
row2 = [ 1, 1, 1, 1, 5, 5, 5, 7, 7,11, 5, 7, 7,11,11, 11]
col2 = [ 1, 5, 7,11, 5, 7,11, 7, 11,11, 1, 1, 5, 1, 5, 7]
data1.extend(data2)
row1.extend(row2)
col1.extend(col2)
data = scipy.array( data1, dtype='float64')
row = scipy.array( row1, dtype='int8')
col = scipy.array( col1, dtype='int8')
self.kelem = ss.coo_matrix( (data, (row, col)), shape=(12,12))
def calc_out_vecs(self):
self.out_vecs = {}
tmp = {}
for sub in self.model.subcases.values():
E = self.E
A = self.A
L = self.L
ub = self.displ[sub.id](6)
ua = self.displ[sub.id](0)
tmp['axial_stress'] = ( ub - ua ) * (E / L)
tmp['axial_force'] = A * tmp['axial_stress']
self.out_vecs[sub.id] = tmp
| Python |
import sympy
from sympy import Matrix
sympy.var(' cosa cosb cosg sina sinb sing ')
Ra = Matrix([[1 , 0 , 0],
[0 ,cosa,sina],
[0,-sina,cosa]])
Rb = Matrix([[cosb, 0,-sinb],
[0 , 1, 0 ],
[sinb,0,cosb ]])
Rg = Matrix([[cosg, sing, 0],
[-sing,cosg,0],
[0,0,1]])
Rab = Ra*Rb
Rabg = Rab*Rg
print 'Rab',Rab
print 'Rabg',Rabg
| Python |
import alg3dpy
from mapy.reader import user_setattr
from mapy.model.elements import Elements
class Elem2D(Elements):
__slots__ = [ 'plane' ]
def __init__(self):
super( Elem2D, self ).__init__()
self.xvec = None
self.yvec = None
self.zvec = None
def rebuild(self):
Elements.rebuild(self)
self.grids = []
g1 = self.model.griddict[int(self.g1)]
g2 = self.model.griddict[int(self.g2)]
g3 = self.model.griddict[int(self.g3)]
self.grids = [g1, g2, g3]
if getattr(self, 'g4', False) <> False:
g4 = self.model.griddict[int(self.g4)]
self.grids.append( g4 )
diag1 = g3 - g1
diag2 = g2 - g4
self.xvec = diag1 + diag2
else:
self.xvec = alg3dpy.vec2points( g1, g2 )
for grid in self.grids:
grid.elements[ self.id ] = self
self.calc_vecs()
#self.calc_Rmatrix()
def calc_vecs(self):
#zvec
# FIXME, for more distorted elements this routine should allow a zvec
# which is the average of many zvecs getting many triangles connecting a
# central point to each pair of adjacent vertices, until the whole
# element is evaluated
grids = self.grids
self.plane = alg3dpy.plane3points( grids[0], grids[1], grids[2] )
self.zvec = self.plane.normal
#yvec
self.yvec = alg3dpy.ortvec2vecs( self.zvec, self.xvec )
| Python |
from mapy.model.elements import Elements
class Elem3d(Elements):
def __init__(self):
Elements.__init__(self)
pass
| Python |
import numpy as np
from mapy.model.elements.elem2d import Elem2D
from mapy.reader import user_setattr
from mapy.constants import FLOAT
class IsoQuad(Elem2D):
'''
Only membrane components considered up to now
The bending terms have to be added
This formulation allows the use of quad elements
from 4 up to 9 nodes
'''
def __init__(self, inputs):
super( IsoQuad, self ).__init__()
self.xis = None
self.yis = None
self.zis = None
self.ng = 9
def rebuild(self):
xis = np.zeros(9, dtype=FLOAT)
yis = np.zeros(9, dtype=FLOAT)
zis = np.zeros(9, dtype=FLOAT)
for i in range( len(self.grids) ):
g = self.grids[i]
xis[i] = g.array[0]
yis[i] = g.array[1]
zis[i] = g.array[2]
self.xis = xis.transpose()
self.yis = yis.transpose()
self.zis = zis.transpose()
self.ng = len(self.grids)
def calc_jacob(self):
def calc_k_rs(self, r, s):
'''
During numerical integration the stiffness matrix is calculated
for many points r, s inside the element.
This function will calculate the k_rs during the numerical integration
'''
h1 = r*(r+1) * s*(s+1) / 4.
h2 = -r*(r-1) * s*(s+1) / 4.
h3 = r*(r-1) * s*(s-1) / 4.
h4 = -r*(r+1) * s*(s-1) / 4.
h5 = -(r**2-1) * s*(s+1) / 2.
h6 = -r*(r-1) * (s**2-1) / 2.
h7 = -(r**2-1) * s*(s-1) / 2.
h8 = -r*(r+1) * (s**2-1) / 2.
h9 = -(r**2-1) * (s**2-1) / 2.
h = np.array( [h1, h2, h3, h4, h5, h6, h7, h8, h9], dtype = FLOAT)
h = h[ :self.ng ]
#
h1r = (2*r+1) * s*(s+1) / 4.
h2r = -(2*r-1) * s*(s+1) / 4.
h3r = (2*r-1) * s*(s-1) / 4.
h4r = -(2*r+1) * s*(s-1) / 4.
h5r = -2*r * s*(s+1) / 2.
h6r = -(2*r-1) * (s**2-1) / 2.
h7r = -2*r * s*(s-1) / 2.
h8r = -(2*r+1) * (s**2-1) / 2.
h9r = 2*r * (s**2-1)
#
hr_u = np.array( [h1r, 0, h2r, 0, h3r, 0,
h4r, 0, h5r, 0, h6r, 0,
h7r, 0, h8r, 0, h9r, 0 ], dtype = FLOAT)
hr_u = hr_u[ : 2*self.ng ]
hr_v = np.array( [ 0, h1r, 0, h2r, 0, h3r,
0, h4r, 0, h5r, 0, h6r,
0, h7r, 0, h8r, 0, h9r ], dtype = FLOAT)
hr_v = hr_v[ : 2*self.ng ]
#
h1s = r*(r+1) * (2*s+1) / 4.
h2s = -r*(r-1) * (2*s+1) / 4.
h3s = r*(r-1) * (2*s-1) / 4.
h4s = -r*(r+1) * (2*s-1) / 4.
h5s = -(r**2-1) * (2*s+1) / 2.
h6s = -r*(r-1) * 2*s / 2.
h7s = -(r**2-1) * (2*s-1) / 2.
h8s = -r*(r+1) * 2*s / 2.
h9s = (r**2-1) * 2*s
#
hs_u = np.array( [h1s, 0, h2s, 0, h3s, 0,
h4s, 0, h5s, 0, h6s, 0,
h7s, 0, h8s, 0, h9s, 0 ], dtype = FLOAT)
hs_u = hs_u[ : 2*self.ng ]
hs_v = np.array( [ 0, h1s, 0, h2s, 0, h3s,
0, h4s, 0, h5s, 0, h6s,
0, h7s, 0, h8s, 0, h9s ], dtype = FLOAT)
hs_v = hs_v[ : 2*self.ng ]
#
dxdr = hr*self.xis
dxds = hs*self.xis
dydr = hr*self.yis
dyds = hs*self.yis
# 3D case not implemented
#dzdr = hr*self.zis
#dzds = hs*self.zis
#jac_rs = np.array(\
# [ [dxdr, dydr, dzdr],
# [dxds, dyds, dzds],
# [dxdt, dydt, dzdt] ], dtype=FLOAT)
jac_rs = np.matrix(\
[ [dxdr, dydr],
[dxds, dyds] ], dtype=FLOAT)
det_jac_rs = np.linalg.det( jac_rs )
jac_inv = jac_rs.getI()
drdx = jac_inv[0][0]
dsdx = jac_inv[0][1]
drdy = jac_inv[1][0]
dsdy = jac_inv[1][1]
# considering b for epslon xx, epslon yy and gama xy
b_rs = np.array(\
[ drdx * hr_u + dsdx * hs_u,
drdy * hr_v + dsdy * hs_v,
drdy * hr_u + dsdy * hs_u + drdx * hr_v + dsdx * hs_v ],
dtype = FLOAT )
#TODO calc constitutive matrix
k_rs = det_jac_rs * np.dot( np.dot( b_rs.transpose(), c ), b_rs )
return k_rs
def jacobian( self, r, s ):
#
| Python |
from mapy.model.elements import Elements
#
class Elem1D(Elements):
'''Elem1D include methods and attributes for all one dimensional
elements.
'''
def __init__(self):
Elements.__init__(self)
def rebuild(self):
Elements.rebuild(self)
self.grids = []
g1 = self.model.griddict[int(self.g1)]
g2 = self.model.griddict[int(self.g2)]
self.grids = [g1, g2]
self.calc_xvec()
self.L = self.grids[0].distfrom( self.grids[1] )
def calc_xvec(self):
g1 = self.grids[0]
g2 = self.grids[1]
self.xvec = g2 - g1
def calc_vecs(self):
self.zvec = self.xvec.cross( self.ovec )
self.yvec = self.zvec.cross( self.xvec )
| Python |
import numpy
from numpy import sqrt
GL = {\
'tria':{\
3:[[[2/3.,1/6.,1/6.],1/3.],
[[1/6.,2/3.,1/6.],1/3.],
[[1/6.,1/6.,2/3.],1/3.]],
4:[[[1/3.,1/3.,1/3.],-0.5625],
[[ 0.6, 0.2, 0.2],25/48.],
[[ 0.2, 0.6, 0.2],25/48.],
[[ 0.2, 0.2, 0.6],25/48.]],
6:[[[0.816847572980459,0.091576213509771,0.091576213509771],0.109951743655322],
[[0.091576213509771,0.816847572980459,0.091576213509771],0.109951743655322],
[[0.091576213509771,0.091576213509771,0.816847572980459],0.109951743655322],
[[0.108103018168070,0.445948490915965,0.445948490915965],0.223381589678011],
[[0.108103018168070,0.445948490915965,0.445948490915965],0.223381589678011],
[[0.108103018168070,0.445948490915965,0.445948490915965],0.223381589678011]
],
7:[[[1/3.,1/3.,1/3.],0.225],
[[0.797426985353087,0.101286507323456,0.101286507323456],0.125939180544827],
[[0.101286507323456,0.797426985353087,0.101286507323456],0.125939180544827],
[[0.101286507323456,0.101286507323456,0.797426985353087],0.125939180544827],
[[0.059715871789770,0.470142064105115,0.470142064105115],0.132394152788506],
[[0.470142064105115,0.059715871789770,0.470142064105115],0.132394152788506],
[[0.470142064105115,0.470142064105115,0.059715871789770],0.132394152788506],
]},
'uni':{\
1:[[0. , 2. ]],
2:[[-1./sqrt(3) , 1. ],
[ 1./sqrt(3) , 1. ]],
3:[[-sqrt(3/5.) , 5/9. ],
[ 0. , 8/9. ],
[ sqrt(3/5.) , 5/9. ]],
4:[[-sqrt(3-2*sqrt(6/5.)/7.) , (18.+sqrt(30.))/36. ],
[ sqrt(3-2*sqrt(6/5.)/7.) , (18.+sqrt(30.))/36. ],
[-sqrt(3+2*sqrt(6/5.)/7.) , (18.-sqrt(30.))/36. ],
[ sqrt(3+2*sqrt(6/5.)/7.) , (18.-sqrt(30.))/36. ]],
5:[[ 0. , 128/225. ],
[-(1/3.) * sqrt(5-2*sqrt(10/7.)) , (322.+13*sqrt(70.))/900. ],
[ (1/3.) * sqrt(5-2*sqrt(10/7.)) , (322.+13*sqrt(70.))/900. ],
[-(1/3.) * sqrt(5+2*sqrt(10/7.)) , (322.-13*sqrt(70.))/900. ],
[ (1/3.) * sqrt(5+2*sqrt(10/7.)) , (322.-13*sqrt(70.))/900. ]]}}
| Python |
from mapy.model.elements.elem1d import Elem1D
from mapy.reader import user_setattr
from mapy.constants import FLOAT, INT
class ElemRod(Elem1D):
'''Defines a rod element, which is a truss including the axial
torsion.
'''
def __init__(self, inputs):
Elem1D.__init__(self)
self = user_setattr(self, inputs)
def rebuild(self):
Elem1D.rebuild(self)
self.A = self.pobj.a
self.E = self.pobj.matobj.e
self.calc_Rmatrix()
self.build_kelem()
def build_kelem(self):
import scipy
import scipy.sparse as ss
#FIXME add J and the respective stiffness matrix terms
A = self.A
E = self.E
L = self.L
eal = E*A/L
data = scipy.array([ eal,-eal,-eal, eal], dtype=FLOAT )
row = scipy.array([ 0, 6, 0, 6], dtype=INT )
col = scipy.array([ 0, 0, 6, 6], dtype=INT )
self.kelem = ss.coo_matrix( (data, (row, col)), shape=(12,12))
def calc_out_vecs(self):
self.out_vecs = {}
tmp = {}
for sub in self.model.subcases.values():
E = self.E
A = self.A
L = self.L
ub = self.displ[sub.id](6)
ua = self.displ[sub.id](0)
tmp['axial_stress'] = ( ub - ua ) * (E / L)
tmp['axial_force'] = A * tmp['axial_stress']
self.out_vecs[sub.id] = tmp
| Python |
import alg3dpy
class Elements(object):
__slots__ = [ 'id', 'model', 'xvec', 'yvec', 'zvec', 'mask', 'tmp', \
'grids', 'cg', 'pobj', 'entryclass', 'card', 'panel' ]
def __init__(self):
self.grids = []
self.mask = False
self.panel = None
def rebuild(self):
if getattr(self, 'pid', False) <> False:
prop = self.model.propdict[int(self.pid)]
self.pobj = prop
def calc_cg(self):
self.cg = alg3dpy.Point( [0,0,0] )
for grid in self.grids:
self.cg.x1 += grid.x1
self.cg.x2 += grid.x2
self.cg.x3 += grid.x3
N = len(self.grids)
self.cg.x1 /= N
self.cg.x2 /= N
self.cg.x3 /= N
def add2model(self, model):
self.model = model
model.elemdict[self.id] = self
def calc_Rmatrix(self):
import scipy
import scipy.sparse as ss
# a --> alpha, b --> beta, g --> gama
cosb = alg3dpy.cosplanevec(alg3dpy.XY, self.xvec)
sinb = alg3dpy.sinplanevec(alg3dpy.XY, self.xvec)
cosg = alg3dpy.cosplanevec(alg3dpy.XZ, self.xvec)
sing = alg3dpy.sinplanevec(alg3dpy.XZ, self.xvec)
if self.__class__.__name__.find('ElemRod') == -1:
Y2 = alg3dpy.Y * cosg - alg3dpy.X * sing
cosa = alg3dpy.cos2vecs(Y2, self.yvec)
sina = alg3dpy.sin2vecs(Y2, self.yvec)
else:
cosa = 1.
sina = 0.
gridnum = scipy.array(len(self.grids),dtype='int8')
dim = gridnum * 6
tmp = scipy.array(\
[ cosb*cosg , cosb*sing , -sinb ,
-cosa*sing+cosg*sina*sinb, cosa*cosg+sina*sinb*sing, cosb*sina,
sina*sing+cosa*cosg*sinb, -cosg*sina+cosa*sinb*sing, cosa*cosb],\
dtype='float32')
row = scipy.array([0, 0, 0, 1, 1, 1, 2, 2, 2], dtype='int8')
col = scipy.array([0, 1, 2, 0, 1, 2, 0, 1, 2], dtype='int8')
self.Rcoord2el = ss.coo_matrix((tmp, (row, col)), shape = (3,3),\
dtype='float32')
self.Rcoord2global = self.Rcoord2el.transpose()
#
data = scipy.array(scipy.zeros( 18*gridnum ))
for i in xrange( gridnum ):
for j in xrange(9):
data[ 18*i + j ] = tmp[j]
row = scipy.array(\
[i for i in xrange(dim) for j in xrange( 3 )], dtype='int8')
col = scipy.array(\
[j + int(i/3)*3 for i in xrange(dim) for j in xrange( 3 )],
dtype='int8')
#self.R2el converts from the global to the elements'
self.R2el = ss.coo_matrix((data, (row, col)), shape = (dim,dim),
dtype='float32')
self.R2global = self.R2el.transpose()
def build_k(self):
import scipy
import scipy.sparse as ss
self.kelem = ss.coo_matrix( self.kelem )
R = self.R2el.tocsc()
Rinv = self.R2global.tocsc()
kelem = self.kelem.tocsc()
k = np.dot( Rinv, kelem )
k = np.dot( k, R )
self.k = k.tocoo()
def calc_displ(self):
self.displ = {}
for sub in self.model.subcases.values():
displ = scipy.zeros(0)
for grid in self.grids:
count = 0
lst = [count*6 for i in xrange(6)]
scipy.insert( displ, lst, grid.displ[sub.id] )
count += 1
self.displ[sub.id] = self.R2el * displ
| Python |
import sympy
sympy.var('u v csi eta u1 u2 u3 u4 u5 u6 v1 v2 v3 v4 v5 v6')
sympy.var('c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 c12')
sympy.var('x1 x2 x3 x4 x5 x6 y1 y2 y3 y4 y5 y6')
#finding 'ci's
eq1 = - u1 + c1 + c2* x1 + c3* y1 + c4* x1*y1 + c5* x1*x1 + c6* y1*y1
eq2 = - u2 + c1 + c2* x2 + c3* y2 + c4* x2*y2 + c5* x2*x2 + c6* y2*y2
eq3 = - u3 + c1 + c2* x3 + c3* y3 + c4* x3*y3 + c5* x3*x3 + c6* y3*y3
eq4 = - u4 + c1 + c2* x4 + c3* y4 + c4* x4*y4 + c5* x4*x4 + c6* y4*y4
eq5 = - u5 + c1 + c2* x5 + c3* y5 + c4* x5*y5 + c5* x5*x5 + c6* y5*y5
eq6 = - u6 + c1 + c2* x6 + c3* y6 + c4* x6*y6 + c5* x6*x6 + c6* y6*y6
eq7 = - v1 + c7 + c8* x1 + c9* y1 + c10* x1*y1 + c11* x1*x1 + c12* y1*y1
eq8 = - v2 + c7 + c8* x2 + c9* y2 + c10* x2*y2 + c11* x2*x2 + c12* y2*y2
eq9 = - v3 + c7 + c8* x3 + c9* y3 + c10* x3*y3 + c11* x3*x3 + c12* y3*y3
eq10 = - v4 + c7 + c8* x4 + c9* y4 + c10* x4*y4 + c11* x4*x4 + c12* y4*y4
eq11 = - v5 + c7 + c8* x5 + c9* y5 + c10* x5*y5 + c11* x5*x5 + c12* y5*y5
eq12 = - v6 + c7 + c8* x6 + c9* y6 + c10* x6*y6 + c11* x6*x6 + c12* y6*y6
ans = sympy.solve((eq1,eq2,eq3,eq4,eq5,eq6,eq7,eq8,eq9,eq10,eq11,eq12),\
c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12)
c1 = ans[c1]
c2 = ans[c2]
c3 = ans[c3]
c4 = ans[c4]
c5 = ans[c5]
c6 = ans[c6]
c7 = ans[c7]
c8 = ans[c8]
c9 = ans[c9]
c10 = ans[c10]
c11 = ans[c11]
c12 = ans[c12]
u = c1 + c2*x + c3*y + c4*xy + c5*x**2 + c6*y**2
v = c7 + c8*x + c9*y + c10*xy + c11*x**2 + c12*y**2
| Python |
from mapy.reader import user_setattr
#
class SPC(object):
__slots__ = ['card','entryclass','id','gridid','dof','displ','g2',
'c2','d2','model','conscount']
def __init__(self, inputs):
self.card = None
self.entryclass = None
self.id = None
self.gridid = None
self.dof = None
self.displ = None
self.g2 = None
self.c2= None
self.d2 = None
self.model = None
self.conscount = None
self = user_setattr(self, inputs)
if self.dof.__class__.__name__ <> 'list':
str_dof = self.dof
self.dof = set([int(dof) for dof in str_dof])
def add2model(self, model):
self.model = model
model.conscount += 1
self.conscount = model.conscount
model.consdict[model.conscount] = self
#FIXME if g2 , c2 and d2 are given, nothing is done...
if self.g2:
print 'ERROR in SPC application for grid %s!!!' \
% str(self.g2)
def add2grid(self, model):
grid = model.griddict[int(self.gridid)]
subcase = int(self.id)
for dof in self.dof:
grid.add_cons(subcase, dof)
| Python |
import alg3dpy
from mapy.reader import user_setattr
#
class Loads(object):
def __init__(self):
self.subcases = {}
def rebuild(self):
pass
def add2model(self, model):
self.model = model
model.loadcount += 1
self.loadcount = model.loadcount
model.loaddict[model.loadcount] = self
def set_subcase(self, subcase):
self.subcases[subcase.id] = subcase
if self.__class__.__name__.find('Load') > -1:
for combloadid in self.loads:
for load in self.model.loaddict.values():
if load.id == combloadid:
load.set_subcase(subcase)
def add2grid(self):
if self.__class__.__name__.find('Load') > -1:
return False
if self.__class__.__name__.find('Moment') > -1:
ref = 3
else:
ref = 0
grid = self.model.griddict[int(self.gridid)]
for sub in self.subcases.values():
if not sub.loadid in self.model.loaddict.keys():
lf = 1.
else:
load = self.model.loaddict[sub.loadid]
if load.__class__.__name__.find('Load') > -1:
lf = load.scaledict[self.id]
else:
lf = 1.
grid.add_load(sub.id, ref + 1, lf * float(self.x1))
grid.add_load(sub.id, ref + 2, lf * float(self.x2))
grid.add_load(sub.id, ref + 3, lf * float(self.x3))
return True
class Force(Loads):
def __init__(self, inputs):
Loads.__init__(self)
self = user_setattr(self, inputs)
self.lf = {}
self.lf[self.id] = 1.
def rebuild(self):
if getattr(self, 'g1id', False) <> False:
g1id = int(self.g1id)
g2id = int(self.g2id)
self.g1obj = self.model.griddict[g1id]
self.g2obj = self.model.griddict[g2id]
self.calc_x1_x2_x3(model)
else:
self.x1 = float(self.f) * float(self.x1)
self.x2 = float(self.f) * float(self.x2)
self.x3 = float(self.f) * float(self.x3)
def calc_x1_x2_x3(self):
self.vec = alg3dpy.Vec(self.g1obj, self.g2obj)
cosbeta, cosgama = self.vec.cosines_GLOBAL()
senbeta = (1 - cosbeta**2)**0.5
sengama = (1 - cosgama**2)**0.5
self.x1 = float(self.f) * cosgama * cosbeta
self.x2 = float(self.f) * sengama
self.x3 = float(self.f) * cosgama * senbeta
class Moment(Loads):
def __init__(self, inputs):
Loads.__init__(self)
self = user_setattr(self, inputs)
def rebuild(self):
self.x1 = float(self.f) * float(self.x1)
self.x2 = float(self.f) * float(self.x2)
self.x3 = float(self.f) * float(self.x3)
class Load(Loads):
def __init__(self, inputs):
Loads.__init__(self)
self = user_setattr(self, inputs)
self.loads = [int(i) for i in self.loads]
self.scales = [float(i) for i in self.scales]
self.scale_overall = float(self.scale_overall)
def rebuild(self):
self.scaledict = {}
for i in xrange(len(self.loads)):
self.scaledict[self.loads[i]] = self.scales[i] * self.scale_overall
# self.combload = {}
# for i in xrange(len(self.loads)):
# load = int(self.loads[i])
# scale = float(self.scales[i])
# self.combload[load] = self.model.loaddict[load]
# self.combload[load].lf[self.id] = self.scale_overall * self.scale
| Python |
class Subcase(object):
def __init__(self, subid, loadid, consid):
self.id = subid
self.loadid = loadid
self.consid = consid
def rebuild(self):
for load in self.model.loaddict.values():
if load.id == self.loadid:
load.set_subcase(self)
| Python |
from loads import *
from subcases import *
| Python |
from mapy.reader import user_setattr
from alg3dpy import Point
from coords import Coord, CoordR, CoordC, CoordS
from mapy.constants import *
import numpy as np
import random as rdm
class Grid( Point ):
"""
The inheritance from the alg3dpy.Point class exists.
The array attribute is from Point class.
Attributes:
____________________________________________________________________________
card the card name (NASTRAN etc)
entryclass path to the class name
id grid id
rcid reference coordinate system id
rcobj pointer to the reference coordinate system object
x1, x2, x3 coordinates
ocid output coordsys id
ocobj pointer to the ouptut coordsys
perm_cons permanent constraints, applied to all load cases
seid superelement id
cons dictionary that will be filled with all constraints applied
to this grid
loads dictionary that will be filled with all loads applied to
this grid
displ dictionary that will store displacement resiults
pos defines the grid position in the stiffness matrix
(for the solver)
k_offset used by the solver to store positions in the stiffness
matrix, for each subcase
elements all elements connected to this grid
garray stores in a numpy array the original coordinates of this
grid
array point-like coordinates, always given in the basic cartesian
coordinate system, used to create other coordsys
model pointer to the model it belong to
rebuilt pointer to the model it belong to
____________________________________________________________________________
"""
__slots__ = [ 'card','entryclass','id','rcid','rcobj','x1','x2','x3',\
'ocid','ocobj','perm_cons','seid','loads','cons','displ',\
'pos','k_offset', 'elements','garray','array','model' ]
def __init__( self, inputs = {} ):
self.card = None
self.entryclass = None
self.id = int( MAXID*rdm.random() )
self.rcid = None
self.rcobj = None
self.x1 = None
self.x2 = None
self.x3 = None
self.ocid = None
self.ocobj = None
self.perm_cons = set()
self.seid = None
self.cons = {}
self.loads = {}
self.displ = {}
self.pos = -1
self.k_offset = {}
self.elements = {}
self.garray = None
self.array = None
self.model = None
self.rebuilt = False
self = self.read_inputs( inputs )
def read_inputs( self, inputs = {} ):
self = user_setattr(self, inputs)
if self.perm_cons.__class__.__name__ <> 'set':
str_perm_cons = self.perm_cons
self.perm_cons = set([int(dof) for dof in str_perm_cons])
#checking strings
if self.rcid == '' \
or self.rcid == None:
self.rcid = 0
if self.ocid == '' \
or self.ocid == None:
self.ocid = 0
#updating he pointers to CSYSGLOBAL if rcid and ocid == 0
if self.rcid == 0:
self.rcobj = CSYSGLOBAL
if self.ocid == 0:
self.ocobj = CSYSGLOBAL
self.garray = np.array([ self.x1, self.x2, self.x3 ], dtype=FLOAT)
def check_to_rebuild( self ):
self.rcobj = self.model.coorddict[ int(self.rcid) ]
if self.rcobj.rebuilt:
return True
else:
return False
def rebuild( self ):
self.cons = {}
self.loads = {}
self.displ = {}
self.pos = -1
self.k_offset = {}
self.elements = {}
#TODO transformation from degrees to radians
#study in the future if it is better to do all
#transformations at once in a dedicated module
if self.rcobj.rebuilt:
if self.rcobj.card == 'CORD1C' or self.rcobj.card == 'CORD2C':
self.garray[1] = self.garray[1] * np.pi / 180.
if self.rcobj.card == 'CORD1S' or self.rcobj.card == 'CORD2S':
self.garray[1] = self.garray[1] * np.pi / 180.
self.garray[2] = self.garray[2] * np.pi / 180.
array = self.rcobj.transform( self.garray, CSYSGLOBAL )
super( Grid, self ).__init__( array, self.id )
else:
print 'The grid cannot be rebuilt, the coordsys has not'
print 'been updated...'
raise
self.rebuilt = True
def transform( self, new_csys=None ):
"""
This function checks for an existing reference coordinate system and it
performs the transformation if necessary.
See further description in mapy.model.coords.Coord().transform().
"""
if self.rcobj == None:
return self.array
else:
if self.rcobj.rebuilt:
return self.rcobj.transform( self.array, new_csys )
else:
print 'The transformation can not be done.'
print 'The grid rcobj (coordsys) was not rebuilt...'
raise
def add2model( self, model ):
self.model = model
model.griddict[self.id] = self
def add_load( self, sub_id, dof, load ):
if not int(sub_id) in self.loads.keys():
self.loads[sub_id] = [ ZERO for i in xrange(6) ]
self.loads[sub_id][dof - 1] += load
def add_cons( self, sub_id, dof ):
if not int(sub_id) in self.cons.keys():
self.cons[sub_id] = set([])
if not dof in self.cons[sub_id]:
self.cons[sub_id].add(dof)
else:
print 'Duplicated CONSTRAINT for GRID %d, dof %d' % (self.id, dof)
def attach_displ( self, sub_id, displ_vec ):
self.displ[sub_id] = displ_vec
def read_card():
#TODO if it is better to keep the card reading here instead of inside
# mapy.reader
pass
def print_card():
#TODO if it is better to keep the card printing here instead of inside
# mapy.reader or mapy.printer
pass
def print_displ( self, sub_id ):
if sub_id in self.displ.keys():
d = self.displ[sub_id]
print 'GRID,%d,SUB,%d,DISPL,%f,%f,%f,%f,%f,%f' %\
tuple([ self.id , sub_id ] + [t for t in d])
def __str__( self ):
return 'Grid ID %d:\n\
\tCoord Sys ID %d:\n\
\tx1 = %2.3f, x2 = %2.3f, x3 = %2.3f'\
% (self.id, self.rcid, self.array[0], self.array[1], self.array[2])
def __repr__( self ):
return 'mapy.model.Grid class'
| Python |
from alg3dpy.vector import Vec
from alg3dpy.angles import cosplanevec, sinplanevec, cos2vecs, sin2vecs
from alg3dpy.plane import Plane
from alg3dpy.point import Point
import random as rdm
import numpy as np
import mapy
from mapy.reader import user_setattr
from mapy.constants import *
def common__str__(text, csys):
if csys.rebuilt:
return '%s ID %d:\n\
\tO %2.3f i + %2.3f j + %2.3f k\n\
\tX %2.3f i + %2.3f j + %2.3f k\n\
\tY %2.3f i + %2.3f j + %2.3f k\n\
\tZ %2.3f i + %2.3f j + %2.3f k' \
% ( text, csys.id,\
csys.o[0], csys.o[1], csys.o[2],\
csys.x[0], csys.x[1], csys.x[2],\
csys.y[0], csys.y[1], csys.y[2],\
csys.z[0], csys.z[1], csys.z[2] )
else:
return '%s ID %d:\n\
\tNOT REBUILT...'\
% ( text, csys.id )
class Coord(object):
"""
Each coordinate system is defined by three points:
rcid: reference coordinate system in which all the others are
defined. If not given the basic cartesian system will be used.
o: the origin
z: the Z axis
vecxz: a point laying in the azimuthal origin
Basically the point are defined using reference GRIDs or POINT coordinates.
Attributes:
____________________________________________________________________________
card the card name (NASTRAN etc)
entryclass path to the class name
id coordinate system id
rcid reference coordsys id
rcobj pointer to the reference coordsys object
o the origin of the coordsys alg3dpy.Point
x the x vector of the coordsys
y the y vector of the coordsys
z the z vector of the coordsys
xy the xy plane of the coordsys
xz the xz plane of the coordsys
yz the yz plane of the coordsys
vecxz a vector laying in the xz plane of the coordsys
a1, a2, a3 components of the point defining the origin
b1, b2, b3 components of the point defining the y axis
c1, c2, c3 components of the point defining the xz plane
ida, idb id of coordsys "a" or "b" when creating two coordsys in the
same card. In NASTRAN, the cards: CORD1R, CORD1C or CORD1S
g1a, g1b grid defining the origin of coordsys "a" or "b"
g2a, g2b grid defining the z axis of coordsys "a" or "b"
g3a, g3b grid defining the xz plane of coordsys "a" or "b"
model pointer to the model object it belongs to
rebuilt a flag to tell if this coordsys is already rebuilt
____________________________________________________________________________
Note: not all attributes are used simultaneously, but the Coord class is
already prepared for many ways for defining a coordsys
____________________________________________________________________________
"""
__slots__ = [ 'card','entryclass','id','rcid','rcobj','o','x','y','z',
'xy','xz','yz','vecxz',
'a1','a2','a3','b1','b2','b3','c1','c2','c3',
'ida','idb','g1a','g2a','g3a','g1b','g2b','g3b',
'model','rebuilt' ]
def __init__(self, id=None, o=None, rcid=None, z=None, vecxz=None):
self.card = None
self.entryclass = None
inputs = {}
if id.__class__.__name__ == 'dict':
inputs = id
id = None
self.id = id
self.rcid = rcid
self.rcobj = None
self.o = o
self.x = None
self.y = None
self.z = z
self.xy = None
self.xz = None
self.yz = None
self.vecxz = vecxz
self.a1 = None
self.a2 = None
self.a3 = None
self.b1 = None
self.b2 = None
self.b3 = None
self.c1 = None
self.c2 = None
self.c3 = None
self.ida = None
self.idb = None
self.g1a = None
self.g2a = None
self.g3a = None
self.g1b = None
self.g2b = None
self.g3b = None
self.model = None
self.rebuilt = False
self.read_inputs( inputs )
def read_inputs( self, inputs = {} ):
if len(inputs) > 0:
self = user_setattr(self, inputs)
if self.id == None and self.ida <> None:
self.id = int(self.ida)
CSYSGLOBAL = mapy.constants.CSYSGLOBAL
self.rcid = 0
self.rcobj = CSYSGLOBAL
def add2model(self, model):
self.model = model
model.coorddict[self.id] = self
if self.idb <> None\
and self.g1b <> None and self.g2b <> None and self.g3b <> None:
if self.__class__.__name__.find('CoordR') > -1:
newcsys = CoordR( int(self.idb), None, None, None, None )
if self.__class__.__name__.find('CoordC') > -1:
newcsys = CoordC( int(self.idb), None, None, None, None )
if self.__class__.__name__.find('CoordS') > -1:
newcsys = CoordS( int(self.idb), None, None, None, None )
newcsys.ida = self.idb
newcsys.id = self.idb
newcsys.rcid = self.rcid
newcsys.rcobj = self.rcobj
newcsys.card = self.card
newcsys.entryclass = self.entryclass
newcsys.g1a = self.g1b
newcsys.g2a = self.g2b
newcsys.g3a = self.g3b
newcsys.model = model
model.coorddict[newcsys.id] = newcsys
self.idb = None
self.g1b = None
self.g2b = None
self.g3b = None
def check_to_rebuild( self ):
if self.a1 <> None and self.a2 <> None and self.a3 <> None \
and self.b1 <> None and self.b2 <> None and self.b3 <> None \
and self.c1 <> None and self.c2 <> None and self.c3 <> None:
rcobj = self.model.coorddict[ int(self.rcid) ]
if rcobj.rebuilt:
return True
else:
return False
elif self.ida <> None \
and self.g1a <> None and self.g2a <> None and self.g3a <> None:
g1a = self.model.griddict[ int(self.g1a) ]
g2a = self.model.griddict[ int(self.g2a) ]
g3a = self.model.griddict[ int(self.g3a) ]
if not g1a.rebuilt \
or not g2a.rebuilt \
or not g3a.rebuilt:
return False
else:
return True
else:
print 'FIXME'
raise
def rebuild(self, rcobj = None, force_new_axis = False ):
new_axis = False
if self.o == None or self.z == None or self.vecxz == None:
new_axis = True
if not new_axis:
if self.o.__class__.__name__.find('Point') == -1:
self.o = Point( np.array([ 0,0,0 ], dtype=FLOAT ) )
if self.z == None:
print 'Please, enter a valid z axis...'
raise
if self.vecxz == None:
print 'Please, enter a valid vector in the xz plane...'
raise
if self.z.__class__.__name__.find('Vec') == -1:
self.z = Vec( self.z )
if self.vecxz.__class__.__name__.find('Vec') == -1:
self.vecxz = Vec( self.vecxz )
if new_axis or force_new_axis:
if self.model == None:
print 'The coordinate system must belong to a model...'
print 'the user may create a coordsys giving directly:'
print '- origin as a alg3dpy.Point'
print '- z axis as a alg3dpy.Vec'
print '- alg3dpy.Vec laying on xz plane'
raise
if self.a1 <> None and self.a2 <> None and self.a3 <> None \
and self.b1 <> None and self.b2 <> None and self.b3 <> None \
and self.c1 <> None and self.c2 <> None and self.c3 <> None:
self.rcobj = self.model.coorddict[ int(self.rcid) ]
if self.rcobj.rebuilt:
#FIXME destroying the reference to rcobj original
p1 = np.array([self.a1, self.a2, self.a3], dtype=FLOAT)
p2 = np.array([self.b1, self.b2, self.b3], dtype=FLOAT)
p3 = np.array([self.c1, self.c2, self.c3], dtype=FLOAT)
CSYSGLOBAL = mapy.constants.CSYSGLOBAL
p1 = self.rcobj.transform( p1, CSYSGLOBAL )
p2 = self.rcobj.transform( p2, CSYSGLOBAL )
p3 = self.rcobj.transform( p3, CSYSGLOBAL )
self.rcid = CSYSGLOBAL.id
self.rcobj = CSYSGLOBAL
self.o = p1
self.z = p2 - p1
self.vecxz = p3 - p1
else:
print 'The coordsys cannot be rebuilt. The reference'
print 'coordsys given by rcid is not rebuilt...'
raise
elif self.ida <> None\
and self.g1a <> None and self.g2a <> None and self.g3a <> None:
g1a = self.model.griddict[ int(self.g1a) ]
g2a = self.model.griddict[ int(self.g2a) ]
g3a = self.model.griddict[ int(self.g3a) ]
if not g1a.rebuilt \
or not g2a.rebuilt \
or not g3a.rebuilt:
print 'The coordsys cannot be rebuilt. The reference'
print 'grids g1a, g2a and g3a are not rebuilt...'
raise
self.o = Point( g1a.array )
self.z = g2a - g1a
self.vecxz = g3a - g1a
else:
print 'Something wrong with your inputs'
print 'Please, see all the attributes below:'
for slot in self.__slots__:
print '\t' + slot + '', getattr(self, slot)
raise
self.y = self.z.cross( self.vecxz )
self.x = self.y.cross( self.z )
self.xy = Plane( self.z[0], self.z[1], self.z[2], self.o.mod() )
self.xz = Plane( -self.y[0], -self.y[1], -self.y[2], self.o.mod() )
self.yz = Plane( self.x[0], self.x[1], self.x[2], self.o.mod() )
self.rebuilt = True
def transform(self, vec, new_csys):
"""
The transformation will go as follows:
- transform to cartesian in the local coordsys;
- rotate to the new_csys (which is cartesian);
- translate to the new_csys.
All systems: cartesian, cylindrical or spherical; have
the method vec2cr which will automatically transform vec into
cartesian coordinates in the local coordsys.
The two other steps will rotate and translate vec to new_csys.
The last step will transform again from the new_csys cartesian
coordinates to its cylindrical or spherical coordinates.
All coordinate systems have the method cr2me to transform from
local cartesian to local something.
"""
#FIXME modify this to keep the original reference to rcobj
if new_csys == None:
new_csys = CSYSGLOBAL
vec_cr = self.vec2cr( vec )
R = self.Rmatrix( new_csys )
vec_rot = np.dot( R, vec_cr )
vec_t = self.translate( vec_rot, new_csys )
vec_final = new_csys.cr2me( vec_t )
return vec_final
def translate(self, vec, newcr):
"""
Calculates the translation matrix to a new cartesian system (newcr)
"""
vec = Vec( vec )
vec_t = vec + newcr.o + self.o
return vec_t
def Rmatrix(self, newcr):
"""
Calculates the rotation matrix to a new cartesian system (newcr)
"""
cosb = cosplanevec( newcr.xy, self.x )
sinb = sinplanevec( newcr.xy, self.x )
cosg = cosplanevec( newcr.xz, self.x )
sing = sinplanevec( newcr.xz, self.x )
tmpT = np.array([\
[ -sing, ZER, ZER ],
[ ZER, cosg, ZER ],
[ ZER, ZER, ZER ]])
Y2 = Vec( np.dot( tmpT, newcr.y.array ) )
cosa = cos2vecs( Y2, self.y )
sina = sin2vecs( Y2, self.y )
Rself = np.array([\
[ cosb*cosg , cosb*sing , -sinb ], \
[-cosa*sing+cosg*sina*sinb, cosa*cosg+sina*sinb*sing, cosb*sina], \
[ sina*sing+cosa*cosg*sinb, -cosg*sina+cosa*sinb*sing, cosa*cosb]],\
dtype=FLOAT)
R2new = Rself.transpose()
return R2new
def R2basic(self):
return self.Rmatrix( CSYSGLOBAL )
class CoordR(Coord):
def __init__(self, id=None, o=None, rcid=None, z=None, vecxz=None):
super( CoordR, self ).__init__(id, o, rcid, z, vecxz)
def __str__(self):
return common__str__('Cartesian Coord Sys', self)
def vec2cr( self, vec ):
return vec
def cr2me( self, vec ):
return vec
class CoordC(Coord):
def __init__(self, id=None, o=None, rcid=None, z=None, vecxz=None):
super( CoordC, self ).__init__(id, o, rcid, z, vecxz)
def vec2cr( self, vec ):
"""
Transformation from cylindrical to cartesian
vec must be in cylindrical cordinates: [r, theta, z]
"""
T = np.array([\
[ np.cos( vec[1] ), ZER, ZER ],
[ ZER, np.sin( vec[1] ), ZER ],
[ ZER, ZER, ONE ]])
tmp = np.array([ vec[0], vec[0], vec[2] ], dtype=FLOAT)
vec_cr = np.dot( T, tmp )
return vec_cr
def cr2me( self, vec ):
"""
Transformation from cartesian to cylindrical
vec must be in cartesian coordinates: [x, y, z]
"""
T = np.array([\
[ np.sqrt( vec[0] ** 2 + vec[1] ** 2 ), ZER, ZER ],
[ ZER, np.arctan( vec[1] / vec[0] ), ZER ],
[ ZER, ZER, ONE ]])
tmp = np.array([ 1, 1, vec[2] ], dtype=FLOAT)
return np.dot( T, tmp )
def __str__(self):
return common__str__('Cylindrical Coord Sys', self)
class CoordS(Coord):
def __init__(self, id=None, o=None, rcid=None, z=None, vecxz=None):
super( CoordS, self ).__init__(id, o, rcid, z, vecxz)
def vec2cr( self, vec ):
"""
Transformation from spherical to cartesian
vec must be in spherical coordinates: [r, theta, phi]
"""
T = np.array([\
[ np.sin( vec[1] )*np.cos( vec[2] ), ZER, ZER ],
[ ZER, np.sin( vec[1] )*np.sin( vec[2] ), ZER ],
[ ZER, ZER, np.cos( vec[1] ) ]])
tmp = np.array([ vec[0], vec[0], vec[0] ], dtype=FLOAT)
return np.dot( T, tmp )
def cr2me( self, vec ):
"""
Transformation from cartesian to spherical
vec must be in cartesian coordinates: [x, y, z]
"""
h = vec[0] ** 2 + vec[1] ** 2
T = np.array([\
[ np.sqrt( h + vec[2] ** 2 ), ZER, ZER ],
[ ZER, np.arctan( np.sqrt(h) / vec[2] ), ZER ],
[ ZER, ZER, np.arctan( vec[1] / vec[0] ) ]])
tmp = np.array([ 1, 1, 1], dtype=FLOAT)
return np.dot( T, tmp )
def __str__(self):
return common__str__('Spherical Coord Sys', self)
# Weisstein, Eric W. "Rotation Matrix." From MathWorld--A Wolfram Web Resource.
# http://mathworld.wolfram.com/RotationMatrix.html
| Python |
from mapy.reader import user_setattr
from mapy.model.properties import Properties
class Prop1D(Properties):
def __init__(self):
super( Prop1D, self ).__init__()
class PropRod(Prop1D):
def __init__(self, inputs):
super( PropRod, self ).__init__()
self = user_setattr(self, inputs)
def build_C(self):
pass
class PropBar(Prop1D):
def __init__(self, inputs):
super( PropBar, self ).__init__()
self = user_setattr(self, inputs)
def build_C(self):
import numpy
nu = self.matobj.nu
Emat = self.matobj.e
A = self.a
if nu:
Gmat = Emat/(2.*(1+nu))
else:
Gmat = self.matobj.g
self.matobj.nu = Emat/Gmat/2. - 1
self.G = Gmat
#FIXME these k below are valid for rectangular sections only
kxy = 5/6.
kxz = 5/6.
GA = Gmat*A
self.C = A*numpy.array([\
[ Emat , 0 , 0 ],\
[ 0 , GA*kxy , 0 ],\
[ 0 , 0 , GA*kxz]])
| Python |
from mapy.model.properties.prop2d import Prop2D
class PropShellComp(Prop2D):
__slots__ = [ 'card', 'entryclass', 'id', 'z0', 'nsm', 'sbmat', 'ft',
'tref', 'dampc', 'lam', 'midlist', 'tlist', 'thetalist',
'laminate' ]
def __init__(self, inputs):
super( PropShellComp, self ).__init__()
self.card = None
self.entryclass = None
self.id = None
self.z0 = None
self.nsm = None
self.sbmat = None
self.ft = None
self.tref = None
self.dampc = None
self.lam = None
self.midlist = []
self.tlist = []
self.thetalist = []
self = user_setattr(self, inputs)
| Python |
import numpy as np
from lamina import Lamina
from mapy.model.properties import Properties
from mapy.model.materials.matlamina import read_laminaprop
from mapy.constants import ONE, ZER, FLOAT
class Laminate( Properties ):
#TODO update this __slots__
#__slots__ = []
"""
Attributes:
____________________________________________________________________________
id laminate property id
general laminate as general uses the general constitutive equations
laminates list of laminates that can be part of this laminate
plies list of plies
plyt common ply thickness for this laminate
t total thickness of the laminate
e1 equivalent laminate modulus in 1 direction
e2 equivalent laminate modulus in 2 direction
g12 equivalent laminate shear modulus in 12 direction
nu12 equivalent laminate Poisson ratio in 12 direction
nu21 equivalent laminate Poisson ratio in 21 direction
eq_fracts list of porcentages of each orientation
eq_thetas list of angles corresponding to eq_fracts
eq_matobjs list of materials corresponding to eq_fracts
xiA laminate parameters for extensional matrix A
xiB laminate parameters for extension-bending matrix B
xiD laminate parameters for bending matrix D
A laminate extension matrix
B laminate extension-bending matrix
D laminate bending matrix
E laminate transferse shear matrix
ABD laminate ABD matrix
ABDE laminate ABD matrix with transverse shear terms
____________________________________________________________________________
Note:
____________________________________________________________________________
"""
def __init__(self):
super( Laminate, self ).__init__()
self.id = None
self.general = False
self.laminates = []
self.plies = []
self.matobj = None
self.t = None
self.plyt = None
eq_thetas = None
eq_fracts = None
eq_matobjs = None
self.e1 = None
self.e2 = None
self.e3 = None
self.nu12 = None
self.g12 = None
self.g13 = None
self.g23 = None
self.xiA = None
self.xiB = None
self.xiD = None
self.A = None
self.B = None
self.D = None
self.E = None
self.ABD = None
self.ABDE = None
def rebuild( self ):
T = ZER
for ply in self.plies:
ply.rebuild()
T += ply.t
self.t = T
def calc_equivalent_modulus( self ):
AI = np.matrix( self.ABD, dtype=FLOAT ).I
a11, a12, a22, a33 = AI[0,0], AI[0,1], AI[1,1], AI[2,2]
self.e1 = 1./(self.t*a11)
self.e2 = 1./(self.t*a22)
self.g12 = 1./(self.t*a33)
self.nu12 = - a12 / a11
self.nu21 = - a12 / a22
def calc_lamination_parameters( self ):
#
xiA1, xiA2, xiA3, xiA4 = ZER, ZER, ZER, ZER
#
xiB1, xiB2, xiB3, xiB4 = ZER, ZER, ZER, ZER
#
xiD1, xiD2, xiD3, xiD4 = ZER, ZER, ZER, ZER
#
xiE1, xiE2, xiE3, xiE4 = ZER, ZER, ZER, ZER
#
T = ZER
#
for ply in self.plies:
T += ply.t
self.t = T
h0 = -T/2
for ply in self.plies:
#
hk_1 = h0
h0 += ply.t
hk = h0
#
Afac = ply.t / T
Bfac = ( 2. / T**2 ) * ( hk**2 - hk_1**2 )
Dfac = ( 4. / T**3 ) * ( hk**3 - hk_1**3 )
Efac = ( 1. / T ) * ( hk - hk_1 )# * (5./6) * (5./6)
#
cos2t = ply.cos2t
cos4t = ply.cos4t
sin2t = ply.sin2t
sin4t = ply.sin4t
#
xiA1 += Afac * cos2t
xiA2 += Afac * sin2t
xiA3 += Afac * cos4t
xiA4 += Afac * sin4t
#
xiB1 += Bfac * cos2t
xiB2 += Bfac * sin2t
xiB3 += Bfac * cos4t
xiB4 += Bfac * sin4t
#
xiD1 += Dfac * cos2t
xiD2 += Dfac * sin2t
xiD3 += Dfac * cos4t
xiD4 += Dfac * sin4t
#
xiE1 += Efac * cos2t
xiE2 += Efac * sin2t
xiE3 += Efac * cos4t
xiE4 += Efac * sin4t
#
self.xiA = np.array([ ONE, xiA1, xiA2, xiA3, xiA4], dtype=FLOAT)
self.xiB = np.array([ ZER, xiB1, xiB2, xiB3, xiB4], dtype=FLOAT)
self.xiD = np.array([ ONE, xiD1, xiD2, xiD3, xiD4], dtype=FLOAT)
self.xiE = np.array([ ONE, xiE1, xiE2, xiE3, xiE4], dtype=FLOAT)
def calc_ABDE_from_lamination_parameters( self ):
# dummies used to unpack vector results
du1, du2, du3, du4, du5, du6 = ZER, ZER, ZER, ZER, ZER, ZER
# A matrix terms
A11,A22,A12, du1,du2,du3, A66,A16,A26 =\
( self.t ) * np.dot( self.matobj.u, self.xiA )
# B matrix terms
B11,B22,B12, du1,du2,du3, B66,B16,B26 =\
( self.t**2/4. ) * np.dot( self.matobj.u, self.xiB )
# D matrix terms
D11,D22,D12, du1,du2,du3, D66,D16,D26 =\
( self.t**3/12. ) * np.dot( self.matobj.u, self.xiD )
# E matrix terms
du1,du2,du3, E44,E55,E45, du4,du5,du6 =\
( self.t ) * np.dot( self.matobj.u, self.xiE )
#
self.A = np.array( [[ A11, A12, A16 ],
[ A12, A22, A26 ],
[ A16, A26, A66 ]], dtype=FLOAT )
#
self.B = np.array( [[ B11, B12, B16 ],
[ B12, B22, B26 ],
[ B16, B26, B66 ]], dtype=FLOAT )
#
self.D = np.array( [[ D11, D12, D16 ],
[ D12, D22, D26 ],
[ D16, D26, D66 ]], dtype=FLOAT )
#
# printing E acoordingly to Reddy definition for E44, E45 and E55
self.E = np.array( [[ E55, E45 ],
[ E45, E44 ]], dtype=FLOAT )
#
self.ABD = np.array( [[ A11, A12, A16, B11, B12, B16 ],
[ A12, A22, A26, B12, B22, B26 ],
[ A16, A26, A66, B16, B26, B66 ],
[ B11, B12, B16, D11, D12, D16 ],
[ B12, B22, B26, D12, D22, D26 ],
[ B16, B26, B66, D16, D26, D66 ]], dtype=FLOAT )
#
# printing ABDE acoordingly to Reddy definition for E44, E45 and E55
self.ABDE = np.array( [[ A11, A12, A16, B11, B12, B16, ZER, ZER ],
[ A12, A22, A26, B12, B22, B26, ZER, ZER ],
[ A16, A26, A66, B16, B26, B66, ZER, ZER ],
[ B11, B12, B16, D11, D12, D16, ZER, ZER ],
[ B12, B22, B26, D12, D22, D26, ZER, ZER ],
[ B16, B26, B66, D16, D26, D66, ZER, ZER ],
[ ZER, ZER, ZER, ZER, ZER, ZER, E55, E45 ],
[ ZER, ZER, ZER, ZER, ZER, ZER, E45, E44 ]],
dtype=FLOAT )
def calc_ABD_general( self ):
self.A_general = np.zeros([5,5], dtype=FLOAT)
self.A = np.zeros([3,3], dtype=FLOAT)
self.B_general = np.zeros([5,5], dtype=FLOAT)
self.B = np.zeros([3,3], dtype=FLOAT)
self.D_general = np.zeros([5,5], dtype=FLOAT)
self.D = np.zeros([3,3], dtype=FLOAT)
self.E = np.zeros([2,2], dtype=FLOAT)
T = ZER
#
for ply in self.plies:
T += ply.t
self.t = T
h0 = -T/2
for ply in self.plies:
#
hk_1 = h0
h0 += ply.t
hk = h0
for i in range(5):
for j in range(5):
self.A_general[i][j] += ply.QL[i][j]*(hk - hk_1 )
self.B_general[i][j] +=1/2.*ply.QL[i][j]*(hk**2 - hk_1**2)
self.D_general[i][j] +=1/3.*ply.QL[i][j]*(hk**3 - hk_1**3)
for iA, iQ in enumerate([0,1,4]):
for jA,jQ in enumerate([0,1,4]):
self.A[iA][jA] += ply.QL[iQ][jQ] * (hk - hk_1 )
self.B[iA][jA] += 1/2.*ply.QL[iQ][jQ] * (hk**2 - hk_1**2)
self.D[iA][jA] += 1/3.*ply.QL[iQ][jQ] * (hk**3 - hk_1**3)
for iE, iQ in enumerate([2,3]):
for jE, jQ in enumerate([2,3]):
self.E[iE][jE] += ply.QL[iQ][jQ] * (hk - hk_1 )
conc1 = np.concatenate( [ self.A_general, self.B_general ], axis=1 )
conc2 = np.concatenate( [ self.B_general, self.D_general ], axis=1 )
self.ABD_general = np.concatenate( [conc1, conc2], axis=0 )
conc1 = np.concatenate( [ self.A, self.B ], axis=1 )
conc2 = np.concatenate( [ self.B, self.D ], axis=1 )
self.ABD = np.concatenate( [conc1, conc2], axis=0 )
def force_balanced_LP( self ):
ONE, xiA1, xiA2, xiA3, xiA4 = self.xiA
self.xiA = np.array([ ONE, xiA1, ZER, xiA3, ZER], dtype=FLOAT)
self.calc_ABDE_from_lamination_parameters()
def force_symmetric_LP( self ):
self.xiB = np.zeros(5)
self.calc_ABDE_from_lamination_parameters()
def force_balanced( self ):
self.A[0][2] = ZER
self.A[1][2] = ZER
self.A[2][0] = ZER
self.A[2][1] = ZER
self.ABD[0][2] = ZER
self.ABD[1][2] = ZER
self.ABD[2][0] = ZER
self.ABD[2][1] = ZER
self.ABDE[0][2] = ZER
self.ABDE[1][2] = ZER
self.ABDE[2][0] = ZER
self.ABDE[2][1] = ZER
def force_symmetric( self ):
self.B = np.zeros((3,3))
for i in range(0,3):
for j in range(3,6):
self.ABD[i][j] = ZER
self.ABDE[i][j] = ZER
for i in range(3,6):
for j in range(0,3):
self.ABD[i][j] = ZER
self.ABDE[i][j] = ZER
def read_stack( self, stack, plyt, laminaprop = None ):
self.plyt = plyt
self.matobj = read_laminaprop( laminaprop )
self.stack = stack
for theta in self.stack:
ply = Lamina()
ply.theta = np.array( theta, dtype=FLOAT )
ply.t = np.array( self.plyt, dtype=FLOAT )
ply.matobj = self.matobj
self.plies.append( ply )
self.rebuild()
if self.general == False:
self.calc_lamination_parameters()
self.calc_ABDE_from_lamination_parameters()
else:
self.calc_ABD_general()
return self
def read_lamination_parameters( xiA1, xiA2, xiA3, xiA4,
xiB1, xiB2, xiB3, xiB4,
xiD1, xiD2, xiD3, xiD4,
xiE1, xiE2, xiE3, xiE4, laminaprop = None ):
lam.matobj = read_laminaprop( laminaprop )
self.xiA = np.array([ ONE, xiA1, xiA2, xiA3, xiA4 ], dtype=FLOAT)
self.xiB = np.array([ ZER, xiB1, xiB2, xiB3, xiB4 ], dtype=FLOAT)
self.xiD = np.array([ ONE, xiD1, xiD2, xiD3, xiD4 ], dtype=FLOAT)
self.xiE = np.array([ ONE, xiE1, xiE2, xiE3, xiE4 ], dtype=FLOAT)
def read_stack( stack, plyt, laminaprop = None, general = True ):
lam = Laminate()
lam.general = general
lam.read_stack( stack, plyt, laminaprop )
return lam
def read_lamination_parameters( xiA1, xiA2, xiA3, xiA4,
xiB1, xiB2, xiB3, xiB4,
xiD1, xiD2, xiD3, xiD4,
xiE1, xiE2, xiE3, xiE4, laminaprop = None ):
lam = Laminate()
lam.general = False
lam.read_lamination_parameters( xiA1, xiA2, xiA3, xiA4,
xiB1, xiB2, xiB3, xiB4,
xiD1, xiD2, xiD3, xiD4,
xiE1, xiE2, xiE3, xiE4, laminaprop )
return lam
| Python |
from lamina import *
from laminate import *
from pcomp import *
| Python |
import numpy as np
from mapy.constants import ONE, ZER, FLOAT
#
class Lamina(object):
#TODO
# __slots__ = []
"""
Reference: Reddy, J. N., Mechanics of Laminated Composite Plates and
Shells - Theory and Analysys. Second Edition. CRC PRESS, 2004.
Attributes:
____________________________________________________________________________
plyid id of the composite lamina
matobj a pointer to a MatLamina object
t ply thickness
theta ply angle
thetarad False means theta in degrees; True means theta in radians
L transformation matrix for displacements to laminate csys
R transformation matrix for stresses to laminate csys
T transformation matrix for stresses to lamina csys
Q constitutive matrix for plane-stress in lamina csys
QL constitutive matrix for plane-stress in laminate csys
C general constitutive matrix in lamina csys
CL general constitutive matrix in laminate csys
laminates laminates that contain this lamina
cos cos( theta )
cos2t cos( 2*theta )
sin sin( theta )
sin2t sin( 2*theta )
____________________________________________________________________________
Note:
____________________________________________________________________________
"""
def __init__(self):
self.plyid = None
self.matobj = None
self.t = None
self.theta = None
self.thetarad = False
self.L = None
self.R = None
self.T = None
self.Q = None
self.QL = None
self.laminates = []
self.cos = None
self.cos2t = None
self.sin = None
self.sin2t = None
def rebuild( self ):
if self.thetarad:
self.thetarad = False
self.theta = np.rad2deg( self.theta )
self.cos = np.cos( np.deg2rad( self.theta ) )
self.cos2t = np.cos( np.deg2rad( 2*self.theta ) )
self.sin = np.sin( np.deg2rad( self.theta ) )
self.sin2t = np.sin( np.deg2rad( 2*self.theta ) )
#
cos = self.cos
sin = self.sin
cos2 = cos**2
cos3 = cos**3
cos4 = cos**4
sin2t = self.sin2t
sin2 = sin**2
sin3 = sin**3
sin4 = sin**4
sincos = sin*cos
self.L = np.array(\
[[ cos, sin, ZER ],
[ -sin, cos, ZER ],
[ ZER, ZER, ONE ]], dtype=FLOAT)
#STRESS
#to lamina
self.R = np.array(\
[[ cos2, sin2, ZER, ZER, ZER, sin2t ],
[ sin2, cos2, ZER, ZER, ZER, -sin2t ],
[ ZER, ZER, ONE, ZER, ZER, ZER ],
[ ZER, ZER, ZER, cos, -sin, ZER ],
[ ZER, ZER, ZER, sin, cos, ZER ],
[ -sincos, sincos, ZER, ZER, ZER, cos2-sin2 ]],dtype=FLOAT)
#to laminate
self.T = np.array(\
[[ cos2, sin2, ZER, ZER, ZER, -sin2t ],
[ sin2, cos2, ZER, ZER, ZER, sin2t ],
[ ZER, ZER, ONE, ZER, ZER, ZER ],
[ ZER, ZER, ZER, cos, sin, ZER ],
[ ZER, ZER, ZER, -sin, cos, ZER ],
[ sincos, -sincos, ZER, ZER, ZER, cos2-sin2 ]],dtype=FLOAT)
#STRAINS
#different from stress due to:
# 2*e12 = e6 2*e13 = e5 2*e23 = e4
#to laminate
#self.Rstrain = np.transpose( self.Tstress )
#to lamina
#self.Tstrain = np.transpose( self.Rstress )
if self.matobj.__class__.__name__ == "MatLamina":
e1 = self.matobj.e1
e2 = self.matobj.e2
e3 = self.matobj.e3
nu12 = self.matobj.nu12
nu21 = self.matobj.nu21
nu13 = self.matobj.nu13
nu31 = self.matobj.nu31
nu23 = self.matobj.nu23
nu32 = self.matobj.nu32
g12 = self.matobj.g12
g13 = self.matobj.g13
g23 = self.matobj.g23
else:
e1 = self.matobj.e
e2 = self.matobj.e
nu12 = self.matobj.nu
nu21 = self.matobj.nu
g12 = self.matobj.g
g = self.matobj.g
# GENERAL CASE
self.C = self.matobj.c
self.CL = np.dot( np.dot( self.T, self.C ), self.T.transpose() )
# PLANE STRESS
# from references:
# Reddy, J. N., Mechanics of laminated composite plates and shells.
# Theory and analysis. Second Edition. CRC Press, 2004.
q11 = e1/(1-nu12*nu21)
q12 = nu12*e2/(1-nu12*nu21)
q22 = e2/(1-nu12*nu21)
q44 = g23
q55 = g13
q16 = ZER
q26 = ZER
q66 = g12
#
self.Q = np.array(\
[[ q11, q12, q16, ZER, ZER ],
[ q12, q22, q26, ZER, ZER ],
[ q16, q26, q66, ZER, ZER ],
[ ZER, ZER, ZER, q44, ZER ],
[ ZER, ZER, ZER, ZER, q55 ]], dtype=FLOAT )
#
q11L = q11*cos4 + 2*(q12 + 2*q66)*sin2*cos2 + q22*sin4
q12L = (q11 + q22 - 4*q66)*sin2*cos2 + q12*(sin4 + cos4)
q22L = q11*sin4 + 2*(q12 + 2*q66)*sin2*cos2 + q22*cos4
q16L = (q11 - q12 - 2*q66)*sin*cos3 + (q12 - q22 + 2*q66)*sin3*cos
q26L = (q11 - q12 - 2*q66)*sin3*cos + (q12 - q22 + 2*q66)*sin*cos3
q66L = (q11 + q22 - 2*q12 - 2*q66)*sin2*cos2 + q66*(sin4 + cos4)
q44L = q44*cos2 + q55*sin2
q45L = (q55 - q44)*sincos
q55L = q55*cos2 + q44*sin2
#
self.QL = np.array(\
[[ q11L, q12L, q16L, ZER, ZER ],
[ q12L, q22L, q26L, ZER, ZER ],
[ q16L, q26L, q66L, ZER, ZER ],
[ ZER, ZER, ZER, q44L, q45L ],
[ ZER, ZER, ZER, q45L, q55L ]], dtype=FLOAT )
self.TQ = np.array(\
[[ cos2, sin2, -sin2t, ZER, ZER ],
[ sin2, cos2, sin2t, ZER, ZER ],
[ sincos, -sincos, cos2-sin2, ZER, ZER ],
[ ZER, ZER, ZER, cos, sin ],
[ ZER, ZER, ZER, -sin, cos ]], dtype=FLOAT )
self.RQ = np.array(\
[[ cos2, sin2, sin2t, ZER, ZER ],
[ sin2, cos2, -sin2t, ZER, ZER ],
[ -sincos, sincos, cos2-sin2, ZER, ZER ],
[ ZER, ZER, ZER, cos, -sin ],
[ ZER, ZER, ZER, sin, cos ]], dtype=FLOAT )
self.QL2 = np.dot( np.dot( self.TQ, self.Q ), self.TQ.transpose() )
#
#TODO add the thermal coeficient terms when calculating the
#stresses... to discount eventual thermal expansions /
#contractions
def C2lamina( self, C ):
return np.dot( np.dot( self.Tstress, C ), np.transpose(self.Tstress) )
def S2lamina( self, S ):
return np.dot( np.dot( np.transpose(self.Rstress), S ), self.Rstress )
class EqLamina( object ):
"""
Attributes:
____________________________________________________________________________
id laminate property id
laminates list of laminates that can be part of this laminate
plies list of plies
t total thickness of the laminate
eq_fracts list of porcentages of each orientation
eq_thetas list of angles corresponding to eq_fracts
eq_matobjs list of materials corresponding to eq_fracts
____________________________________________________________________________
Note:
____________________________________________________________________________
"""
def __init__(self):
super( Laminate, self ).__init__()
self.id = None
self.laminates = []
self.plies = []
self.t = None
eq_thetas = None
eq_fracts = None
eq_matobjs = None
self.e1 = None
self.e2 = None
self.e3 = None
self.nu12 = None
self.g12 = None
self.g13 = None
self.g23 = None
def eq_laminate( self ):
#checks
norm = False
if sum(eq_fracts) <> 1.:
self.print_warning([
'angle fractions different then 1.',
'automatically normalizing for calculations'])
norm = True
if norm:
fracts = [float(i)/sum(eq_fracts) for i in eq_fracts]
else:
fracts = eq_fracts
#
if len(eq_fracts) <> len(eq_thetas):
self.print_error([
'number of angles differs from number of fractions'])
#
if len(eq_fracts) <> len(eq_matobjs):
self.print_warning([
'numer of matobj differs from number of fractions',
'automatically assigning materials'])
addnum = len( fractions ) - len(eq_matobjs)
matobjref = eq_matobjs[0]
matobjs = []
for i in range( len(eq_fracts) ):
matobjs.append( matobjref )
else:
matobjs = eq_matobjs
#calculating eq_laminate
self.e1 = 0.
self.e2 = 0.
self.e3 = 0.
self.g23 = 0.
self.g13 = 0.
self.g12 = 0.
for i in range( len(eq_thetas) ):
fract = fracts[i]
theta = thetas[i]
matobj = matobjs[i]
ply = Lamina()
ply.matobj = matobj
ply.theta = theta
ply.calc_lamina()
Rt = ply.R.transpose()
lamina_eng = np.array(\
[[ matobj.e1 ],
[ matobj.e2 ],
[ ONE ],
[ matobj.g23 ],
[ matobj.g13 ],
[ matobj.g12 ]] , dtype = FLOAT)
e1,e2,e3,g23,g13,g12 = np.dot( np.dot( Rt, ply.T ), lamina_eng )
self.e1 += e1 * fract
self.e2 += e2 * fract
self.e3 += e3 * fract
self.g23 += g23 * fract
self.g13 += g13 * fract
self.g12 += g12 * fract
| Python |
#
class Properties(object):
def __init__(self):
pass
def rebuild(self):
if getattr(self, 'mid', False) <> False:
self.matobj = self.model.matdict[int(self.mid)]
self.build_C()
def add2model(self, model):
self.model = model
model.propdict[self.id] = self
def print_warning(self, lines):
print 'WARNING: see property %d' % self.id
for line in lines:
print ' ' + line
def print_error(self, lines):
print 'ERROR : see property %d' % self.id
for line in lines:
print ' ' + line
| Python |
from mapy.reader import user_setattr
from mapy.model.properties import Properties
#
class Prop2D(Properties):
def __init__(self):
super( Prop2D, self ).__init__()
class PropShell(Prop2D):
def __init__(self, inputs):
super( PropShell, self).__init__()
self = user_setattr(self, inputs)
def build_C(self):
import scipy
Emat = self.matobj.e
if self.matobj.nu:
Gmat = Emat/(2.*(1+self.matobj.nu))
else:
Gmat = self.matobj.g
self.matobj.nu = Emat/Gmat/2. - 1
nu = self.matobj.nu
self.C = (Emat/(1-nu**2)) * scipy.array([\
[ 1 , nu , 0],\
[nu , 1 , 0],\
[0 , 0 , (1-nu)/2]])
| Python |
import time
import os
import alg3dpy.scipy_sparse as assparse
import constraints
from mapy.constants import CSYSGLOBAL
def get_cons(grid, sub_id):
if sub_id in grid.cons.keys():
if len(grid.perm_cons) > 0:
cons = list(grid.perm_cons | grid.cons[sub_id])
else:
cons = list(grid.cons[sub_id])
else:
cons = list(grid.perm_cons)
cons.sort()
return cons
#TODO para encontrar elementos / nos mais proximos
#
#TODO
# cria classe cubos
# determinados em funcao das coordenadas min e max do modelos
# cada cubo leva a lista dos elementos que serao considerados nas varreduras
# cada cubo tem os atributos xmin xmax ymin ymax zmin zmax
#TODO
# varredura direcional obtendo-se os elementos adjacentes e escolhendo qual
# direcao e melhor no sentido de reduzir a distancia
#
class Model(object):
__slots__ = [ 'name','coorddict','griddict','elemdict','matdict',
'propdict','loaddict','loadcount','consdict','conscount',
'subcases','k_pos','k_offset','index_to_delete','k_coo',
'k_coo_sub','F','fv' ]
def __init__(self, name='default_name'):
self.name = name
self.coorddict = {}
self.griddict = {}
self.elemdict = {}
self.matdict = {}
self.propdict = {}
self.loaddict = {}
self.loadcount = 0
self.consdict = {}
self.conscount = 0
self.subcases = {}
self.k_pos = None
self.k_offset = None
self.index_to_delete = None
self.k_coo = None
self.k_coo_sub = {}
self.F = {}
self.fv = None
CSYSGLOBAL.model = self
self.coorddict[0] = CSYSGLOBAL
def add_subcase(self, id, loadid, consid):
import loads
self.subcases[int(id)] = loads.Subcase(id, loadid, consid)
self.subcases[int(id)].model = self
def rebuild(self):
"""
Add direct object references for all entries
Grids <--> CoordSys loops. They are processed in the following order:
- basic grids and the basic coord sys
- grids depending on the basic coord sys
loop:
- coord sys depending on these grids
- grids depending on these coord sys
until all grids and coordsys are processed
ERRORS:
- Grids that make reference to an unexisting coordsys
- CoordSys that make reference to an unexisting grid
DEFINITIONS:
- basic coord sys are those created from vectors which are
defined in the basic coordinate system (id=0),
or those which g1, g2 and g3 are basic grids
- basic grids are those making reference to the basic
coordinate system (id=0)
"""
import rebuild
rebuild.rebuild( self )
def build_k(self):
'''
Build the global stiffness matrix
'''
print time.ctime() + ' started - building grid positions in global stiffness matrix'
self.build_k_pos()
print time.ctime() + ' finished - building grid positions in global stiffness matrix'
print time.ctime() + ' started - building lists of constraints'
self.build_index_to_delete()
print time.ctime() + ' finished - building lists of constraints'
print time.ctime() + ' started - building global K stiffness matrix'
self.build_k_coo()
self.build_k_coo_sub()
print time.ctime() + ' finished - building global K stiffness matrix'
print time.ctime() + ' started - building global F load matrices'
self.build_F()
print time.ctime() + ' finished - building global F load matrices'
def build_k_pos(self):
pos = -1
k_pos = []
for elem in self.elemdict.values():
for grid in elem.grids:
if grid.pos == -1:
pos += 1
grid.pos = pos
k_pos.append( grid.id )
k_offset = {}
for sub in self.subcases.values():
k_offset[sub.id] = []
offset = 0
for i in xrange(len(k_pos)):
if i > 0:
gi_1_id = k_pos[ i-1 ]
gi_1 = self.griddict[ gi_1_id ],
'subcases'
cons = get_cons( gi_1 , sub.id )
offset += len( cons )
k_offset[sub.id].append( offset )
gi_id = k_pos[ i ]
gi = self.griddict[ gi_id ]
gi.k_offset[sub.id] = offset
self.k_pos = k_pos
self.k_offset = k_offset
def build_index_to_delete(self):
self.index_to_delete = {}
for sub in self.subcases.values():
index_to_delete = []
for gid in self.k_pos:
grid = self.griddict[gid]
pos = grid.pos
cons = get_cons(grid,sub.id)
for dof in cons:
index_to_delete.append( pos * 6 + (dof-1) )
index_to_delete.sort()
self.index_to_delete[sub.id] = index_to_delete
def build_k_coo(self):
import scipy
import scipy.sparse as ss
dim = 6 * len(self.k_pos)
data = scipy.zeros(shape=0, dtype='float64')
row = scipy.zeros(shape=0, dtype='int64')
col = scipy.zeros(shape=0, dtype='int64')
for elem in self.elemdict.values():
elem.build_k()
for i in xrange(len(elem.grids)):
gi = elem.grids[i]
for j in xrange(len(elem.grids)):
gj = elem.grids[j]
k_grid = assparse.in_sparse(elem.k,i*6,i*6+5,j*6,j*6+5)
#
for d, r, c, in zip(k_grid.data, k_grid.row, k_grid.col):
newr = r + gi.pos * 6
newc = c + gj.pos * 6
data = scipy.append(data, d )
row = scipy.append(row , newr)
col = scipy.append(col , newc)
k_coo = ss.coo_matrix(( data, (row,col) ), shape=(dim,dim))
self.k_coo = k_coo
def build_k_coo_sub(self):
#FIXME if this will be kept... optimize.. there are too many loops
#TOOOOOO SLOW
self.k_coo_sub = {}
for sub in self.subcases.values():
k = self.k_coo
count = -1
for row, col, in zip( k.row, k.col ):
count += 1
for grid_id in self.k_pos:
grid = self.griddict[grid_id]
pos = grid.pos
cons = get_cons( grid, sub.id )
for i in cons:
j = (i - 1) + pos*6
if row == j or col == j:
if row == col:
k.data[count] = 1.
else:
k.data[count] = 0.
self.k_coo_sub[sub.id] = k
def build_F(self):
self.F = {}
for sub in self.subcases.values():
dim = self.k_coo_sub[sub.id].shape[1]
self.F[sub.id] = scipy.zeros(shape=dim, dtype='float64')
itd = self.index_to_delete
for gid in self.k_pos:
grid = self.griddict[gid]
grid_load = grid.loads
for sub in self.subcases.values():
if sub.id in grid_load.keys():
loads = grid_load[sub.id]
k_offset = grid.k_offset[sub.id]
cons = get_cons(grid, sub.id)
sub_i = 0
for i in xrange(6):
index = i + grid.pos*6
self.F[sub.id][index] = loads[i]
# if not (i+1) in cons:
# index = i + grid.pos*6 - k_offset - sub_i
# self.F[sub.id][index] = loads[i]
# else:
# sub_i += 1
def print_displ(self, sub_id = 'all'):
if sub_id == 'all':
for sub in self.subcases.values():
for grid in self.griddict.values():
grid.print_displ(sub.id)
else:
for grid in self.griddict.values():
grid.print_displ(sub_id)
def elem_out_vecs(self):
for elem in self.elemdict.values():
elem.calc_displ()
elem.calc_out_vecs()
def createfemview(self):
import mapy
self.fv = mapy.renderer.FEMView(self)
def TOBEFIXED_build_k_coo_sub(self):
import scipy
import scipy.sparse as ss
#FIXME not considering pos to build the matrix!!!
self.k_coo_sub = {}
for sub in self.subcases.values():
dim = 6*len( self.k_pos ) - \
len( self.index_to_delete[ sub.id ] )
data = scipy.zeros(0, dtype='float64')
row = scipy.zeros(0, dtype='int64')
col = scipy.zeros(0, dtype='int64')
for elem in self.elemdict.values():
numg = len( elem.grids )
for i in xrange( numg ):
gi = elem.grids[ i ]
offseti = gi.k_offset[ sub.id ]
consi = set( [] )
if sub.id in gi.cons.keys():
consi = gi.cons[ sub.id ]
for j in xrange( numg ):
gj = elem.grids[ j ]
offsetj = gj.k_offset[ sub.id ]
consj = set( [] )
if sub.id in gj.cons.keys():
consj = gj.cons[ sub.id ]
cons = consi | consj
index_to_delete = [ (c-1) for c in cons ]
k_grid = assparse.in_sparse(elem.k,i*6,i*6+5,j*6,j*6+5)
if len(index_to_delete) < 6:
k = k_grid
for d, r, c, in zip( k.data , k.row, k.col ):
#FIXME remove the search below
if not r in index_to_delete:
sub_r = 0
for k in index_to_delete:
if r > k:
sub_r += 1
if not c in index_to_delete:
sub_c = 0
for m in index_to_delete:
if c > m:
sub_c += 1
newr = r + gi.pos * 6 - offseti - sub_r
newc = c + gj.pos * 6 - offsetj - sub_c
data = scipy.append( data , d )
row = scipy.append( row , newr )
col = scipy.append( col , newc )
k_coo = ss.coo_matrix(( data, (row,col) ), shape=(dim,dim))
self.k_coo_sub[sub.id] = k_coo
import grids
import elements
import constraints
import loads
import materials
import properties
| Python |
import numpy as np
from mapy.model.materials import Materials
from mapy.reader import user_setattr
from mapy.constants import ONE, ZER, FLOAT
class MatLamina(Materials):
"""
Defines a lamina material.
Attributes:
____________________________________________________________________________
card the card name (NASTRAN etc)
entryclass path to the class name
id material id
e1 Young Modulus in direction 1
e2 Young Modulus in direction 2
g12 in-plane shear modulus
g13 transverse shear modulus for plane 1-Z
g23 transverse shear modulus for plane 2-Z
nu12 Poisson's ratio 12
nu13 Poisson's ratio 13
nu23 Poisson's ratio 23
nu21 Poisson's ratio 21: use formula nu12/e1 = nu21/e2
nu31 Poisson's ratio 31: use formula nu31/e3 = nu13/e1
nu32 Poisson's ratio 32: use formula nu23/e2 = nu32/e3
rho especific mass (mass / volume)
a1 thermal expansion coeffiecient in direction 1
a2 thermal expansion coeffiecient in direction 2
a3 thermal expansion coeffiecient in direction 3
tref reference temperature
damp structural damping coefficient
st1,st2 allowable tensile stresses for directions 1 and 2
sc1,sc2 allowable compressive stresses for directions 1 and 2
ss12 allowable in-plane stress for shear
strn allowable strain for direction 1
q11 lamina constitutive constant 11
q12 lamina constitutive constant 12
q13 lamina constitutive constant 13
q21 lamina constitutive constant 21
q22 lamina constitutive constant 22
q23 lamina constitutive constant 23
q31 lamina constitutive constant 31
q32 lamina constitutive constant 32
q33 lamina constitutive constant 33
q44 lamina constitutive constant 44
q55 lamina constitutive constant 55
q66 lamina constitutive constant 66
u matrix with lamina invariants
c matrix with lamina stiffness coefficients
____________________________________________________________________________
Note: when the user defines "nu" and "g", the "g" will be recaculated
based on equation: e = 2*(1+nu)*g
____________________________________________________________________________
"""
__slots__ = ['card','entryclass','id',
'e1','e2','e3','g12','g13','g23',
'nu12','nu13','nu21','nu23','nu31','nu32','rho',
'a1','a2','a3','tref','damp','st1','st2','sc1','sc2',
'ss12','strn',
'q11','q12','q13','q21','q22','q23','q31','q32','q33',
'q44','q55','q66','u','c']
def __init__( self ):
super( MatLamina, self ).__init__()
self.id = None
self.e1 = None
self.e2 = None
self.e3 = ZER
self.g12 = None
self.g13 = None
self.g23 = None
self.nu12 = None
self.nu13 = ZER
self.nu21 = None
self.nu23 = ZER
self.nu31 = ZER
self.nu32 = ZER
self.rho = None
self.a1 = None
self.a2 = None
self.a3 = None
self.tref = None
self.damp = None
self.st1 = None
self.st2 = None
self.sc1 = None
self.sc2 = None
self.ss12 = None
self.strn = None
self.q11 = None
self.q12 = None
self.q13 = None
self.q21 = None
self.q22 = None
self.q23 = None
self.q31 = None
self.q32 = None
self.q33 = None
self.q44 = None
self.q55 = None
self.q66 = None
self.u = None
def rebuild (self):
#
# from references:
# Reddy, J. N., Mechanics of laminated composite plates and shells.
# Theory and analysis. Second Edition. CRC Press, 2004.
e1 = self.e1
e2 = self.e2
e3 = self.e3
nu12 = self.nu12
nu21 = self.nu21
nu13 = self.nu13
nu31 = self.nu31
nu23 = self.nu23
nu32 = self.nu32
delta = (1-nu12*nu21-nu23*nu32-nu31*nu13-2*nu21*nu32*nu13)/(e1*e2)
c11 = (1 - nu23*nu23)/(delta*e2)
c12 = (nu21 + nu31*nu23)/(delta*e2)
c13 = (nu31 + nu21*nu32)/(delta*e2)
c22 = (1 - nu13*nu31)/(delta*e1)
c23 = (nu32 + nu12*nu31)/(delta*e1)
c33 = e3*(1 - nu12*nu21)/(delta*e1*e2)
c44 = self.g23
c55 = self.g13
c66 = self.g12
self.c = np.array(
[[ c11, c12, c13, ZER, ZER, ZER ],
[ c12, c22, c23, ZER, ZER, ZER ],
[ c13, c23, c33, ZER, ZER, ZER ],
[ ZER, ZER, ZER, c44, ZER, ZER ],
[ ZER, ZER, ZER, ZER, c55, ZER ],
[ ZER, ZER, ZER, ZER, ZER, c66 ]], dtype = FLOAT )
self.c = np.array(
[[ c11, c12, c13, ZER, ZER, ZER ],
[ c12, c22, c23, ZER, ZER, ZER ],
[ c13, c23, c33, ZER, ZER, ZER ],
[ ZER, ZER, ZER, c44, ZER, ZER ],
[ ZER, ZER, ZER, ZER, c55, ZER ],
[ ZER, ZER, ZER, ZER, ZER, c66 ]], dtype = FLOAT )
#
# from references:
# hansen_hvejsen_2007 page 43
#
# Guerdal Z., R. T. Haftka and P. Hajela (1999), Design and
# Optimization of Laminated Composite Materials, Wiley-Interscience.
den = (1 - self.nu12 * self.nu21\
- self.nu13 * self.nu31\
- self.nu23 * self.nu32\
- self.nu12 * self.nu23 * self.nu31\
- self.nu13 * self.nu21 * self.nu32)
den = np.array( den, dtype=FLOAT )
self.q11 = self.e1*( 1 - self.nu23 * self.nu32 ) / den
self.q12 = self.e1*( self.nu21 + self.nu23 * self.nu31 ) / den
self.q13 = self.e1*( self.nu31 + self.nu21 * self.nu32 ) / den
self.q21 = self.e2*( self.nu12 + self.nu13 * self.nu32 ) / den
self.q22 = self.e2*( 1 - self.nu13 * self.nu31 ) / den
self.q23 = self.e2*( self.nu32 + self.nu12 * self.nu31 ) / den
self.q31 = self.e3*( self.nu13 + self.nu12 * self.nu32 ) / den
self.q32 = self.e3*( self.nu23 + self.nu13 * self.nu21 ) / den
self.q33 = self.e3*( 1 - self.nu12 * self.nu21 ) / den
self.q44 = self.g12
self.q55 = self.g23
self.q66 = self.g13
#
# from reference:
# Jones R. M. (1999), Mechanics of Composite Materials, second edn,
# Taylor & Francis, Inc., 325 Chestnut Street, Philadelphia,
# PA 19106. ISBN 1-56032-712-X
# slightly changed to include the transverse shear terms u6 ans
# u7, taken from ABAQUS Example Problems Manual, vol1,
# example 1.2.2 Laminated composite shell: buckling of a
# cylindrical panel with a circular hole
#
u1 = (3*self.q11 + 3*self.q22 + 2*self.q12 + 4*self.q44) / 8
u2 = (self.q11 - self.q22) / 2
u3 = (self.q11 + self.q22 - 2*self.q12 - 4*self.q44) / 8
u4 = (self.q11 + self.q22 + 6*self.q12 - 4*self.q44) / 8
u5 = (u1-u4) / 2
u6 = (self.q55 + self.q66) / 2
u7 = (self.q55 - self.q66) / 2
self.u = np.array(
[[ u1, u2, ZER, u3, ZER ], # q11
[ u1, -u2, ZER, u3, ZER ], # q22
[ u4, ZER, ZER, -u3, ZER ], # q12
[ u6, u7, ZER, ZER, ZER ], # q55
[ u6, -u7, ZER, ZER, ZER ], # q66
[ ZER, ZER, -u7, ZER, ZER ], # q56
[ u5, ZER, ZER, -u3, ZER ], # q44
[ ZER, ZER, u2/2, ZER, u3 ], # q14
[ ZER, ZER, u2/2, ZER, -u3 ]], dtype=FLOAT) # q24
def read_inputs( self, inputs={} ):
if len( inputs ) > 0:
self = user_setattr( self, inputs )
if not self.nu21:
nu21 = np.array( self.nu12*self.e2/self.e1, dtype=FLOAT )
self.nu21 = nu21
if not self.nu12:
nu12 = np.array( self.nu21*self.e1/self.e2, dtype=FLOAT )
self.nu12 = nu12
def read_laminaprop( laminaprop = None, rebuild=True ):
matlam = MatLamina()
#laminaProp = ( e1, e2, nu12, g12, g13, g23, tempref, e3, nu13, nu23 )
#laminaProp units N/mm2
if laminaprop == None:
print 'ERROR - laminaprop must be a tuple in the following format:'
print ' ( e1, e2, nu12, g12, g13, g23, tempref, e3, nu13, nu23 )'
if len(laminaprop) == 7:
laminaprop = tuple( list(laminaprop) + [ZER, ZER, ZER] )
matlam.e1 = np.array( laminaprop[0], dtype=FLOAT )
matlam.e2 = np.array( laminaprop[1], dtype=FLOAT )
matlam.e3 = np.array( laminaprop[7], dtype=FLOAT )
matlam.nu12 = np.array( laminaprop[2], dtype=FLOAT )
matlam.nu13 = np.array( laminaprop[8], dtype=FLOAT )
matlam.nu23 = np.array( laminaprop[9], dtype=FLOAT )
nu21 = matlam.nu12 * matlam.e2 / matlam.e1
nu31 = matlam.nu13 * matlam.e3 / matlam.e1
nu32 = matlam.nu23 * matlam.e3 / matlam.e2
matlam.nu21 = np.array( nu21 , dtype=FLOAT )
matlam.nu31 = np.array( nu31 , dtype=FLOAT )
matlam.nu32 = np.array( nu32 , dtype=FLOAT )
matlam.g12 = np.array( laminaprop[3], dtype=FLOAT )
matlam.g13 = np.array( laminaprop[4], dtype=FLOAT )
matlam.g23 = np.array( laminaprop[5], dtype=FLOAT )
if rebuild:
matlam.rebuild()
return matlam
| Python |
from mapy.model.materials import Materials
from mapy.reader import user_setattr
class MatIso(Materials):
"""
Defines an isotropic material.
Attributes:
____________________________________________________________________________
card the card name (NASTRAN etc)
entryclass path to the class name
id material id
e Young Modulus
g shear modulus
nu Poisson's ratio
rho especific mass (mass / volume)
a thermal expansion coeffiecient
tref reference temperature
damp structural damping coefficient
st allowable stress for tension
sc allowable stress for compression
ss allowable stress for shear
mcsid material coordinate system NOT USED
____________________________________________________________________________
Note: when the user defines "nu" and "g", the "g" will be recaculated
based on equation: e = 2*(1+nu)*g
____________________________________________________________________________
"""
__slots__ = ['card','entryclass','id','e','g','nu','rho','a','tref',
'damp','st','sc','ss','mcsid']
def __init__( self, id=None, e=None, nu=None ):
super( MatIso, self ).__init__()
self.id = id
self.e = e
self.nu = nu
self.g = None
self.rho = None
self.a = None
self.tref = None
self.dampcoe = None
self.st = None
self.sc = None
self.ss = None
self.mcsid = None
def read_inputs( self, inputs = {} ):
if len( inputs ) > 0:
self = user_setattr( self, inputs )
| Python |
#
class Materials(object):
def __init__( self ):
pass
def add2model( self, model ):
self.model = model
model.matdict[self.id] = self
| Python |
import time
def rebuild(self):
#########################################################
# Grid <--> CoordSys loops
print time.ctime() + ' started - rebuilding grids and coordsys'
# first processing basic grids and coordsys
for grid in self.griddict.values():
if grid.rcid == 0 or grid.rcid == '':
grid.rebuild()
loop = True
if loop:
all_done = 0
while all_done < 3:
all_done += 1
for grid in self.griddict.values():
if not grid.rebuilded:
if grid.check_to_rebuild():
grid.rebuild()
if all_done > 0:
all_done = 0
for coord in self.coorddict.values():
if not coord.rebuilded:
if coord.check_to_rebuild():
coord.rebuild()
if all_done > 0:
all_done = 0
print time.ctime() + ' finished - rebuilding grids and coordsys'
#########################################################
for prop in self.propdict.values():
prop.rebuild()
print time.ctime() + ' finished - rebuilding properties'
print time.ctime() + ' started - rebuilding elements'
for elem in self.elemdict.values():
elem.rebuild()
print time.ctime() + ' finished - rebuilding elements'
print time.ctime() + ' started - rebuilding subcases'
for sub in self.subcases.values():
sub.rebuild()
print time.ctime() + ' finished - rebuilding subcases'
print time.ctime() + ' started - rebuilding load entities'
for load in self.loaddict.values():
load.rebuild()
load.add2grid()
print time.ctime() + ' finished - rebuilding load entities'
print time.ctime() + ' started - rebuilding constraints'
for cons in self.consdict.values():
cons.add2grid(self)
print time.ctime() + ' finished - rebuilding constraints'
| Python |
import cylinder
| Python |
import os
os.system('cls')
import mapy
home = os.environ['HOME']
modelpath = \
os.path.join( home, 'programming', 'python', 'modeling-analysis-python',
'tests', 'rods_spiral_many_coords.dat' )
fem1 = mapy.FEM()
fem1.create_model()
fem1.read_new_file( modelpath )
fem1.model.rebuild()
tmp = []
for coord in fem1.model.coorddict.values():
print coord
tmp.append( [ coord.id, coord.rcobj.id ] )
#for tmpi in tmp:
# print tmpi
tmp = []
for grid in fem1.model.griddict.values():
tmp.append( [ grid.id, grid.array ] )
tmp.sort()
for tmpi in tmp:
print tmpi, fem1.model.griddict[ tmpi[0] ].garray
| Python |
from django import forms
from django.utils.translation import ugettext_lazy as _
class ContactForm(forms.Form):
name = forms.CharField()
email = forms.EmailField()
topic = forms.CharField()
message = forms.CharField(widget=forms.Textarea())
| Python |
#!/usr/bin/env python
import sys
import os
try:
import settings
except ImportError:
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n" % __file__)
sys.exit(1)
def run(settings):
if not os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'third-party') in sys.path:
sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'third-party'))
if not os.path.dirname(os.path.dirname(os.path.abspath(__file__))) in sys.path:
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from django.core.management import execute_manager
execute_manager(settings)
if __name__ == "__main__":
run(settings)
| Python |
from django.db import models
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _
from django_model_utils.fields import TemplateString, TemplateStringField
from django_model_utils.models import StatMixin, PageMixin
class Page(StatMixin, PageMixin, models.Model):
title = models.CharField(max_length=150, verbose_name=_('Titel'))
url = models.CharField(verbose_name=_('URL'), max_length=150, db_index=True, unique=True)
base_template = models.CharField(verbose_name=_('Basis Template'), max_length=200, blank=True, null=True)
content = TemplateStringField(verbose_name=_('Inhalt'), context_callback=lambda p: {'page': p})
@property
def template(self):
base_template = 'page/base.html'
if self.base_template:
base_template = self.base_template
content = self.content.content
if not '{% block' in content:
content = u'{%% block content %%}\n%s\n{%% endblock %%}' % content
return TemplateString(
u'{%% extends "%s" %%}\n%s\n' (base_template, content),
self.content.taglibs,
self.content.context_callback,
self.content.parent_object,
)
def __unicode__(self):
return u"%s -- %s" % (self.url, self.title)
class Meta:
verbose_name = _(u'Statische Seite')
verbose_name_plural = _(u'Statische Seiten')
ordering = ('url',)
| Python |
from django.conf.urls.default import *
urlpatterns = pattern('gironimo.page.views',
url(r'^(?P<url>.*)$', 'view_page', name='page'),
)
| Python |
from django.contrib import admin
from django import forms
from django.utils.translation import ugettext_lazy as _
from gironimo.page.models import Page
class PageAdminForm(forms.ModelForm):
url = forms.RegexField(label=_('URL'), max_length=100, regex=r'^[-\w/_\.]+$',
help_text=_("Beispiel: '/about/contact'. Sicherstellen das ein vorangegangenes Slash angegeben ist."),
error_message=_('Nur Zahlen, Buchstaben, Querstriche, Unterstriche und Slashes erlaubt.'))
def clean_base_template(self):
from django.template.loader import find_template_source
from django.template import TemplateDoesNotExist
value = self.cleaned_data.get('base_template')
if value:
try:
find_template_source(value)
except TemplateDoesNotExist:
raise forms.ValidationError(_(u'Template existiert nicht.'))
return value
class Meta:
model = Page
class PageAdmin(admin.ModelAdmin):
form = PageAdminForm
fieldsets = [
(None, {'fields': ['title', 'url', 'base_template', 'content',]}),
(_('HTML'), {'fields': ['html_title', 'html_description', 'html_keywords',], 'classes': ['collapse']}),
]
list_display = ('title', 'created', 'url', 'base_template')
search_fields = ['title',]
date_hierarchy = 'created'
list_filter = ['created', 'base_template',]
admin.site.register(Page, PageAdmin)
| Python |
from django.http import *
from django.shortcuts import *
from django.template import RequestContext
from gironimo.page.models import Page
def view_page(request, url=''):
from django import template
try:
page = Page.objects.get(url=u'/%s' % url)
except Page.DoesNotExist:
raise Http404()
return HttpResponse(page.template.render(context_instance=RequestContext(request)))
| Python |
#!/usr/bin/env python
import sys
import os
try:
import settings
except ImportError:
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n" % __file__)
sys.exit(1)
def run(settings):
if not os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'third-party') in sys.path:
sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'third-party'))
if not os.path.dirname(os.path.dirname(os.path.abspath(__file__))) in sys.path:
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from django.core.management import execute_manager
execute_manager(settings)
if __name__ == "__main__":
run(settings)
| Python |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django_model_utils.models import StatMixin, PageMixin
class Category(StatMixin, PageMixin, models.Model):
'''
This app creates categories to our webproject. They have a name and a slug
and maybe a description, but this is optionally. All categories will get an
absolute_url so we can display all entries in one category.
'''
name = models.CharField(verbose_name=_('Name'), max_length=150)
slug = models.SlugField(max_length=150, unique=True)
content = models.TextField(verbose_name=_('Beschreibung'))
# ---
# TODO: get all entries within one category
# ----
def __unicode__(self):
return self.name
@models.permalink
def get_absolute_url(self):
return 'category_detail', (), {'slug': self.slug}
class Meta:
verbose_name = _(u'Kategorie')
verbose_name_plural = _(u'Kategorien')
| Python |
from django.conf.urls.defaults import *
urlpatterns = patterns('gironimo.category.views',
url(r'^(?P<slug>[a-z0-9_-]+)/$', 'detail', name='category_detail'),
url(r'^$', 'index', name='category_index'),
)
| Python |
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from gironimo.category.models import Category
class CategoryAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['name', 'slug', 'content',]}),
(_('HTML'), {'fields': ['html_title', 'html_description', 'html_keywords',], 'classes': ['collapse']}),
]
list_display = ('name', 'created',)
search_fields = ['name',]
date_hierarchy = 'created'
prepopulated_fields = {'slug': ('name',),}
list_filter = ['created',]
admin.site.register(Category, CategoryAdmin)
| Python |
from django.shortcuts import render_to_response
from django.template import RequestContext
from gironimo.category.models import Category
def detail(request, slug):
pass
def index(request):
categories = Category.objects.all().order_by('name')
return render_to_response('category/index.html', {
'categories': categories,}, context_instance=RequestContext(request))
| Python |
from django.conf.urls.defaults import patterns, include, url
from django.conf import settings
urlpatterns = patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
url(r'^admin/', include('gironimo.admin_urls')),
url(r'^account/', include('gironimo.account.urls')),
url(r'^kategorie/', include('gironimo.category.urls')),
url(r'^kommentare/', include('django.contrib.comments.urls')),
url(r'^kontakt/$', 'gironimo.views.contact', name='contact'),
url(r'^kontakt/danke/$', 'gironimo.views.contact_thx', name='contact_thx'),
url(r'^galerie/', include('gironimo.gallery.urls')),
url(r'^$', 'gironimo.views.index', name='index'),
)
| Python |
import os.path
DEBUG = True
TEMPLATE_DEBUG = DEBUG
gettext_noop = lambda s: s
ADMINS = (
# ('Your Name', 'your_email@example.com'),
('Marc Rochow', 'kontakt@gironimo.org'),
('Patrick Menrath', 'patrick.menrath@hs-augsburg.de')
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': os.path.join(os.path.dirname(__file__), 'sqlite.db'), # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Europe/Berlin'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'de-de'
LANGUAGES = (
('de', gettext_noop('German')),
)
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
USE_THOUSAND_SEPERATOR = False
LOCALE_PATHS = (
os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))), 'locale'),
)
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'htdocs', 'media')
LIB_MEDIA_ROOT = MEDIA_ROOT
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/admin/media/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = '@rh(p7-nip60a7_$p7+5cs9a)ni15qtwt@8zm_k5*#!&+_i4n7'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'gironimo.gallery.upload_middleware.SWFUploadMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
ROOT_URLCONF = 'gironimo.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(os.path.dirname(os.path.dirname(__file__)), 'templates'),
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.comments',
# Admin,
'django.contrib.admin',
'django.contrib.admindocs',
# Third-Party,
'south',
'django_model_utils',
'tagging',
# gironimo,
'gironimo.account',
'gironimo.category',
'gironimo.gallery',
'gironimo.page',
'gironimo.imagequery',
'gironimo.blog',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.contrib.messages.context_processors.messages',
)
# Account
ACCOUNT_ACTIVATION_DAYS = 7
AUTH_PROFILE_MODULE = 'account.UserProfile'
LOGIN_REDIRECT_URL = '/account/profile/'
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
# imagequery
IMAGEQUERY_DEFAULT_OPTIONS = {'quality': 92}
#E-mail
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
try:
from local_settings import *
except ImportError:
try:
from gironimo.local_settings import *
except ImportError:
pass
| Python |
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'gironimoDB',
'USER': 'root',
'PASSWORD': 'Gironimo7.',
'HOST': '',
'PORT': '',
}
}
| Python |
import os
import weakref
try:
from PIL import Image
from PIL import ImageFile
from PIL import ImageEnhance
from PIL import ImageDraw
except ImportError:
import Image
import ImageFile
import ImageEnhance
import ImageDraw
from django.conf import settings
from django.utils.encoding import smart_str
from django.core.files.base import File, ContentFile
from django.db.models.fields.files import FieldFile
from imagequery import operations
from imagequery.settings import CACHE_DIR, DEFAULT_OPTIONS, default_storage,\
default_cache_storage
from imagequery.utils import get_image_object, get_font_object, get_coords
# stores rendered images
# keys are hashes of image operations
_IMAGE_REGISTRY = weakref.WeakKeyDictionary()
def _set_image_registry(item, image):
_IMAGE_REGISTRY[item] = image
def _get_image_registry(item):
return _IMAGE_REGISTRY.get(item, None)
class QueryItem(object):
"""
An ImageQuery consists of multiple QueryItem's
Each QueryItem might have an associated Operation (like rescaling the image)
"""
def __init__(self, operation=None):
self._previous = None
self._evaluated_image = None
self._name = None
self._format = None
self.operation = operation
def _get_previous(self):
return self._previous
def _set_previous(self, athor):
prev = self._previous
athor._previous = prev
self._previous = athor
previous = property(_get_previous, _set_previous)
def __iter__(self):
items = [self]
item = self._previous
while not item is None:
items.append(item)
item = item._previous
return reversed(items)
def __unicode__(self):
return u', '.join([unicode(x.operation) for x in self])
def execute(self, image):
evaluated_image = _get_image_registry(self)
if evaluated_image is None:
if self._previous is not None:
image = self._previous.execute(image)
if self.operation is not None:
image = self.operation.execute(image, self)
evaluated_image = image
_set_image_registry(self, evaluated_image)
return evaluated_image
def get_attrs(self):
attrs = {}
if self._previous is not None:
attrs.update(self._previous.get_attrs())
if self.operation is not None:
attrs.update(self.operation.attrs)
return attrs
def format(self, value=None):
if value:
self._format = value
return value
item = self
while item:
if item._format:
return item._format
item = item._previous
return None
def name(self, value=None):
import hashlib
if value:
self._name = value
return value
if self._name:
return self._name
val = hashlib.sha1()
altered = False
item = self
while item:
if item._name: # stop on first named operation
val.update(item._name)
altered = True
break
if item.operation:
val.update(unicode(item))
altered = True
item = item._previous
if altered:
return val.hexdigest()
else:
return None
def get_first(self):
first = self
while first._previous is not None:
first = first._previous
return first
def has_operations(self):
if self.operation:
return True
if self._previous:
return self._previous.has_operations()
return False
class RawImageQuery(object):
""" Base class for raw handling of images, needs an loaded PIL image """
def __init__(self, image, source=None, storage=default_storage, cache_storage=None):
self.image = get_image_object(image, storage)
self.source = smart_str(source)
self.storage = storage
if cache_storage is None:
if default_cache_storage is None:
cache_storage = storage
else:
cache_storage = default_cache_storage
self.cache_storage = cache_storage
self.query = QueryItem()
def _basename(self):
if self.source:
return os.path.basename(self.source)
else:
# the image was not loaded from source. create some name
import hashlib
md5 = hashlib.md5()
md5.update(self.image.tostring())
return '%s.png' % md5.hexdigest()
def _format_extension(self, format):
try:
return self._reverse_extensions.get(format, '')
except AttributeError:
if not Image.EXTENSION:
Image.init()
self._reverse_extensions = {}
for ext, _format in Image.EXTENSION.iteritems():
self._reverse_extensions[_format] = ext
# some defaults for formats with multiple extensions
self._reverse_extensions.update({
'JPEG': '.jpg',
'MPEG': '.mpeg',
'TIFF': '.tiff',
})
return self._reverse_extensions.get(format, '')
def _name(self):
if self.query.has_operations():
hashval = self.query.name()
format = self.query.format()
# TODO: Support windows?
# TODO: Remove support for absolute path?
if not self.source or self.source.startswith('/'):
name = self._basename()
else:
name = self.source
if format:
ext = self._format_extension(format)
name = os.path.splitext(name)[0] + ext
return os.path.join(CACHE_DIR, hashval, name)
else:
return self.source
def _source(self):
if self.source:
return self.storage.path(self.source)
def _path(self):
if self.source:
return self.cache_storage.path(self._name())
def _url(self):
if self.query.has_operations():
return self.cache_storage.url(self._name())
else:
return self.storage.url(self._name())
def _exists(self):
if self.source and \
self.cache_storage.exists(self._path()):
# TODO: Really support local paths this way?
try:
source_path = self.storage.path(self.source)
cache_path = self.cache_storage.path(self._path())
if os.path.exists(source_path) and \
os.path.exists(cache_path) and \
os.path.getmtime(source_path) > \
os.path.getmtime(cache_path):
return False
except NotImplementedError:
pass
return True
return False
def _apply_operations(self, image):
image = self.query.execute(image)
return image
def _create_raw(self, allow_reopen=True):
if allow_reopen and self._exists(): # Load existing image if possible
return Image.open(self.cache_storage.open(self._name(), 'rb'))
return self._apply_operations(self.image)
def _convert_image_mode(self, image, format):
# TODO: Run this again with all available modes
# TODO: Find out how to get all available modes ;-)
# >>> import Image
# >>> Image.init()
# >>> MODES = ('RGBA', 'RGB', 'CMYK', 'P', '1')
# >>> FOMATS = Image.EXTENSION.values()
# >>> i = Image.open('/some/image')
# >>> for f in FORMATS:
# ... s = []
# ... for m in MODES:
# ... try:
# ... i.convert(m).save('foo', f)
# ... s.append(m)
# ... except:
# ... pass
# ... print "'" + f + "': ('" + "', '".join(s) + "'),"
# ...
MODES = {
'JPEG': ('RGBA', 'RGB', 'CMYK', '1'),
'PCX': ('RGB', 'P', '1'),
'EPS': ('RGB', 'CMYK'),
'TIFF': ('RGBA', 'RGB', 'CMYK', 'P', '1'),
'GIF': ('RGBA', 'RGB', 'CMYK', 'P', '1'),
'PALM': ('P', '1'),
'PPM': ('RGBA', 'RGB', '1'),
'EPS': ('RGB', 'CMYK'),
'BMP': ('RGB', 'P', '1'),
'PPM': ('RGBA', 'RGB', '1'),
'PNG': ('RGBA', 'RGB', 'P', '1'),
'MSP': ('1'),
'IM': ('RGBA', 'RGB', 'CMYK', 'P', '1'),
'TGA': ('RGBA', 'RGB', 'P', '1'),
'XBM': ('1'),
'PDF': ('RGB', 'CMYK', 'P', '1'),
'TIFF': ('RGBA', 'RGB', 'CMYK', 'P', '1'),
}
if format and format in MODES:
if image.mode not in MODES[format]:
# convert to first mode in list, should be mode with most
# features
image = image.convert(MODES[format][0])
return image
def _create(self, name=None, **options):
'''
Recreate image. Does not check whether the image already exists.
'''
if self.query:
if name is None:
name = self._path()
name = smart_str(name)
image = self._create_raw(allow_reopen=False)
format = self.query.format()
if image.format:
format = image.format
elif not format:
format = self.image.format
if not format:
if not Image.EXTENSION:
Image.init()
format = Image.EXTENSION[os.path.splitext(name)[1]]
if not self.cache_storage.exists(name):
self.cache_storage.save(name, ContentFile(''))
if DEFAULT_OPTIONS:
save_options = DEFAULT_OPTIONS.copy()
else:
save_options = {}
save_options.update(options)
# options may raise errors
# TODO: Check this
image = self._convert_image_mode(image, format)
try:
image.save(self.cache_storage.open(name, 'wb'), format, **save_options)
except TypeError:
image.save(self.cache_storage.open(name, 'wb'), format)
def _clone(self):
import copy
# clone = RawImageQuery(
# self.image,
# self.source,
# self.storage,
# self.cache_storage,
# )
clone = copy.copy(self)
clone.query = copy.copy(self.query)
return clone
def _evaluate(self):
if not self._exists():
self._create()
def _append(self, operation):
query = QueryItem(operation)
query._previous = self.query
self.query = query
return self
def __unicode__(self):
return self.url()
def __repr__(self):
return '<ImageQuery %s>' % self._name()
########################################
# Query methods ########################
########################################
def append(self, op):
q = self._clone()
q = q._append(op)
return q
def blank(self,x=None,y=None,color=None):
return self.append(operations.Blank(x,y,color))
def paste(self, image, x=0, y=0, storage=None):
'''
Pastes the given image above the current one.
'''
if storage is None:
storage = self.storage
return self.append(operations.Paste(image,x,y,storage))
def background(self, image, x=0, y=0, storage=None):
'''
Same as paste but puts the given image behind the current one.
'''
if storage is None:
storage = self.storage
return self.append(operations.Background(image,x,y,storage))
def blend(self, image, alpha=0.5, storage=None):
if storage is None:
storage = self.storage
return self.append(operations.Blend(image,alpha,storage))
def resize(self, x=None, y=None, filter=Image.ANTIALIAS):
return self.append(operations.Resize(x,y,filter))
def scale(self, x, y, filter=Image.ANTIALIAS):
return self.append(operations.Scale(x,y,filter))
def crop(self, x, y, w, h):
return self.append(operations.Crop(x,y,w,h))
def fit(self, x, y, centering=(0.5,0.5), method=Image.ANTIALIAS):
return self.append(operations.Fit(x,y,centering,method))
def enhance(self, enhancer, factor):
return self.append(operations.Enhance(enhancer, factor))
def sharpness(self, amount=2.0):
'''
amount:
< 1 makes the image blur
1.0 returns the original image
> 1 increases the sharpness of the image
'''
return self.enhance(ImageEnhance.Sharpness, amount)
def blur(self, amount=1):
#return self.sharpness(1-(amount-1))
return self.append(operations.Blur(amount))
def filter(self, image_filter):
return self.append(operations.Filter(image_filter))
def truecolor(self):
return self.append(operations.Convert('RGBA'))
def invert(self, keep_alpha=True):
return self.append(operations.Invert(keep_alpha))
def flip(self):
return self.append(operations.Flip())
def mirror(self):
return self.append(operations.Mirror())
def grayscale(self):
return self.append(operations.Grayscale())
def alpha(self):
return self.append(operations.GetChannel('alpha'))
def applyalpha(self, alphamap):
return self.append(operations.ApplyAlpha(alphamap))
def composite(self, image, mask, storage=None):
if storage is None:
storage = self.storage
return self.append(operations.Composite(image, mask, storage))
def offset(self, x, y):
return self.append(operations.Offset(x, y))
def padding(self, left, top=None, right=None, bottom=None, color=None):
return self.append(operations.Padding(left, top, right, bottom, color))
def opacity(self, opacity):
return self.append(operations.Opacity(opacity))
def clip(self, start=None, end=None):
return self.append(operations.Clip(start, end))
def shadow(self, color):
#mask = self.alpha().invert()
#return self.blank(color=None).composite(self.blank(color=color), mask)
return self.blank(color=color).applyalpha(self)
def makeshadow(self, x, y, color, opacity=1, blur=1):
shadow = self.shadow(color).opacity(opacity).blur(blur)
return self.background(shadow, x, y)
def save(self, name=None, storage=None, **options):
# create a clone for saving (thus we might change its state)
q = self._clone()
if storage:
q.cache_storage = storage
q._create(name, **options)
# return new clone
return self._clone()
def query_name(self, value):
q = self._clone()
q = q._append(None)
q.query.name(value)
return q
def image_format(self, value):
value = value.upper()
if not Image.EXTENSION:
Image.init()
if not value in Image.EXTENSION.values():
raise RuntimeError('invalid format')
q = self._clone()
q = q._append(None)
q.query.format(value)
return q
# text operations
def text(self, text, x, y, font, size=None, fill=None):
return self.append(operations.Text(text, x, y, font, size, fill))
@staticmethod
def textbox(text, font, size=None):
font = get_font_object(font, size)
text = smart_str(text)
return font.getsize(text)
@staticmethod
def img_textbox(text, font, size=None):
font = get_font_object(font, size)
text = smart_str(text)
try:
imgsize, offset = font.font.getsize(text)
if isinstance(imgsize, int) and isinstance(offset, int):
imgsize = (imgsize, offset)
offset = (0, 0)
except AttributeError:
imgsize = font.getsize(text)
offset = (0, 0)
return (
imgsize[0] - offset[0],
imgsize[1] - offset[1],
), (
-offset[0],
-offset[1],
)
@staticmethod
def textimg(text, font, size=None, fill=None, padding=0, mode='RGBA', storage=default_storage):
font = get_font_object(font, size)
text = smart_str(text)
imgsize, offset = ImageQuery.img_textbox(text, font, size)
bg = [0,0,0,0]
# Workaround: Image perhaps is converted to RGB before pasting,
# black background draws dark outline around text
if fill:
for i in xrange(0, min(len(fill), 3)):
bg[i] = fill[i]
if padding:
imgsize = (imgsize[0] + padding * 2, imgsize[1] + padding * 2)
offset = (offset[0] + padding, offset[1] + padding)
fontimage = Image.new(mode, imgsize, tuple(bg))
draw = ImageDraw.Draw(fontimage)
# HACK
if Image.VERSION == '1.1.5' and isinstance(text, unicode):
text = text.encode('utf-8')
draw.text(offset, text, font=font, fill=fill)
return RawImageQuery(fontimage, storage=storage)
# methods which does not return a new ImageQuery instance
def mimetype(self):
format = self.raw().format
try:
if not Image.MIME:
Image.init()
return Image.MIME[format]
except KeyError:
return None
def width(self):
return self.raw().size[0]
x = width
def height(self):
return self.raw().size[1]
y = height
def size(self):
return self.raw().size
def raw(self):
return self._create_raw()
def name(self):
self._evaluate()
return self._name()
def path(self):
self._evaluate()
return self._path()
def url(self):
self._evaluate()
return self._url()
class NewImageQuery(RawImageQuery):
""" Creates an new (blank) image for you """
def __init__(self, x, y, color=(0,0,0,0), storage=default_storage, cache_storage=None):
image = Image.new('RGBA', (x, y), color)
super(NewImageQuery, self).__init__(image, storage=storage, cache_storage=cache_storage)
class ImageQuery(RawImageQuery):
""" Write your image operations like you would use QuerySet
With ImageQuery you are able to write image manipulations without needing
to learn some low-level API for the most use cases. It allows you to:
* simple manipulation like rescaling
* combining images
* handling text (note: fonts must be available locally)
* even more like creating drop shadows (using the alpha mask)
ImageQuery basicly provides an API similar to the well known QuerySet API,
which means:
* Most methods just return another ImageQuery
* Every bit of your image manipulation chain can be used/saved
* Image manipulations are lazy, they are only evaluated when needed
ImageQuery in addition automaticly stores the results in an cache, so you
don't need to worry about recreating the same image over and over again.
It is possible to use a different storage for caching, so you could - for
example - put all your cached images on an different server while keeping
the original files locally.
"""
def __init__(self, source, storage=default_storage, cache_storage=None):
query = None
self.storage = storage
if cache_storage is None:
if default_cache_storage is None:
cache_storage = storage
else:
cache_storage = default_cache_storage
self.cache_storage = cache_storage
if isinstance(source, File):
self.source = source.name
source.open('rb')
self.fh = source
if isinstance(source, FieldFile):
# we use the field storage, regardless what the constructor
# get as param, just to be safe
self.storage = source.storage
else:
# assume that image is a filename
self.source = smart_str(source)
self.fh = storage.open(self.source, 'rb')
self.query = QueryItem()
def _get_image(self):
try:
return self._image
except AttributeError:
self.fh.open('rb') # reset file access
self._image = Image.open(self.fh)
return self._image
def _set_image(self, image):
self._image = image
image = property(_get_image, _set_image)
| Python |
# we need a models.py file to make the django test runner determine the tests
from imagequery.settings import ALLOW_LAZY_FORMAT, LAZY_FORMAT_CLEANUP_TIME
if ALLOW_LAZY_FORMAT:
from django.db import models
from django.utils.functional import LazyObject
from datetime import datetime, timedelta
try:
import cPickle as pickle
except ImportError:
import pickle
def resolve_lazy(obj):
if isinstance(obj, LazyObject):
obj._setup()
return obj._wrapped
return obj
class LazyFormatManager(models.Manager):
def cleanup(self):
cleanup_time = datetime.now() - timedelta(seconds=LAZY_FORMAT_CLEANUP_TIME)
self.filter(created__lt=cleanup_time).delete()
class LazyFormat(models.Model):
format = models.CharField(max_length=100)
query_data = models.TextField()
created = models.DateTimeField(default=datetime.now)
objects = LazyFormatManager()
def _set_query(self, imagequery):
from imagequery.query import ImageQuery
if not isinstance(imagequery, ImageQuery):
raise TypeError('this only works for ImageQuery')
data = {
'source': imagequery.source,
'storage': resolve_lazy(imagequery.storage),
'cache_storage': resolve_lazy(imagequery.cache_storage),
}
self.query_data = pickle.dumps(data)
def _get_query(self):
from imagequery.query import ImageQuery
try:
data = pickle.loads(str(self.query_data))
except pickle.UnpicklingError:
raise RuntimeError('could not load data')
return ImageQuery(
source=data['source'],
storage=data['storage'],
cache_storage=data['cache_storage'],
)
query = property(_get_query, _set_query)
@models.permalink
def get_absolute_url(self):
return 'imagequery_generate_lazy', (), {'pk': self.pk}
def generate_image_url(self):
from imagequery import formats
format = formats.get(self.format)
return format(self.query).url()
| Python |
class FormatDoesNotExist(Exception):
pass
_formats = {}
def register(name, format):
_formats[name] = format
def get(name):
try:
return _formats[name]
except KeyError:
raise FormatDoesNotExist()
class Format(object):
"""
A Format represents a fixed image manipulation
Format's allow you to define an image manipulation based on ImageQuery. You
can write your own Format's just by extending the Format class and implement
the execute() method.
Example:
from imagequery import formats
class MyShinyNewFormat(formats.Format):
def execute(self, imagequery):
# it's always good to privide a query name, so you can easily
# empty the cache for the format
# (the name will be created as a path in storage)
return imagequery.operation1().operation2().query_name('shiny')
After defining your format you can register it, this is mainly useful when
using the format inside the templates:
formats.register('shiny', MyShinyNewFormat)
Inside the template (outputs the url):
{% load imagequery_tags %}{% image_format "shiny" obj.image %}
Note:
When using Format's yourself (without the templatetags) you should be aware
that you have to pass it an existing ImageQuery. This is needed to simplify
the storage handling, as Format's don't need to care about storage.
Format's mainly provide some methods to be used in your code, like returning
the URL/path of the generated image.
"""
# we don't allow passing filenames here, as this would need us to
# repeat big parts of the storage-logic
def __init__(self, imagequery):
self._query = imagequery
def execute(self, query):
''' needs to be filled by derivates '''
return query
def _execute(self):
try:
return self._executed
except AttributeError:
self._executed = self.execute(self._query)
return self._executed
def name(self):
""" like Imagequery: return the name of the associated file """
return self._execute().name()
def path(self):
""" like Imagequery: return the full path of the associated file """
return self._execute().path()
def url(self):
""" like Imagequery: return the URL of the associated file """
return self._execute().url()
def height(self):
return self._execute().height()
def width(self):
return self._execute().width()
| Python |
import os
try:
from PIL import Image
from PIL import ImageChops
from PIL import ImageOps
from PIL import ImageFilter
from PIL import ImageDraw
except ImportError:
import Image
import ImageChops
import ImageOps
import ImageFilter
import ImageDraw
from imagequery.utils import get_image_object, get_font_object, get_coords
class Operation(object):
"""
Image Operation, like scaling
"""
args = ()
args_defaults = {}
attrs = {}
def __init__(self, *args, **kwargs):
allowed_args = list(self.args)
allowed_args.reverse()
for key in self.args_defaults:
setattr(self, key, self.args_defaults[key])
for value in args:
assert allowed_args, 'too many arguments, only accepting %s arguments' % len(self.args)
key = allowed_args.pop()
setattr(self, key, value)
for key in kwargs:
assert key in allowed_args, '%s is not an accepted keyword argument' % key
setattr(self, key, kwargs[key])
def __unicode__(self):
content = [self.__class__.__name__]
args = '-'.join([str(getattr(self, key)) for key in self.args])
if args:
content.append(args)
return '_'.join(content)
def execute(self, image, query):
return image
class DummyOperation(Operation):
pass
class CommandOperation(Operation):
def file_operation(self, image, query, command):
import tempfile, subprocess
suffix = '.%s' % os.path.basename(query.source).split('.', -1)[1]
whfile, wfile = tempfile.mkstemp(suffix)
image.save(wfile)
rhfile, rfile = tempfile.mkstemp(suffix)
proc = subprocess.Popen(command % {'infile': wfile, 'outfile': rfile}, shell=True)
proc.wait()
image = Image.open(rfile)
return image
class Enhance(Operation):
args = ('enhancer', 'factor')
def execute(self, image, query):
enhancer = self.enhancer(image)
return enhancer.enhance(self.factor)
class Resize(Operation):
args = ('x', 'y', 'filter')
args_defaults = {
'x': None,
'y': None,
'filter': Image.ANTIALIAS,
}
def execute(self, image, query):
if self.x is None and self.y is None:
self.x, self.y = image.size
elif self.x is None:
orig_x, orig_y = image.size
ratio = float(self.y) / float(orig_y)
self.x = int(orig_x * ratio)
elif self.y is None:
orig_x, orig_y = image.size
ratio = float(self.x) / float(orig_x)
self.y = int(orig_y * ratio)
return image.resize((self.x, self.y), self.filter)
class Scale(Operation):
args = ('x', 'y', 'filter')
args_defaults = {
'filter': Image.ANTIALIAS,
}
def execute(self, image, query):
image = image.copy()
image.thumbnail((self.x, self.y), self.filter)
return image
class Invert(Operation):
args = ('keep_alpha',)
def execute(self, image, query):
if self.keep_alpha:
image = image.convert('RGBA')
channels = list(image.split())
for i in xrange(0, 3):
channels[i] = ImageChops.invert(channels[i])
return Image.merge('RGBA', channels)
else:
return ImageChops.invert(image)
class Grayscale(Operation):
def execute(self, image, query):
return ImageOps.grayscale(image)
class Flip(Operation):
def execute(self, image, query):
return ImageOps.flip(image)
class Mirror(Operation):
def execute(self, image, query):
return ImageOps.mirror(image)
class Blur(Operation):
args = ('amount',)
def execute(self, image, query):
for i in xrange(0, self.amount):
image = image.filter(ImageFilter.BLUR)
return image
class Filter(Operation):
args = ('filter',)
def execute(self, image, query):
return image.filter(self.filter)
class Crop(Operation):
args = ('x', 'y', 'w', 'h')
def execute(self, image, query):
box = (
self.x,
self.y,
self.x + self.w,
self.y + self.h,
)
return image.crop(box)
class Fit(Operation):
args = ('x', 'y', 'centering', 'method')
args_defaults = {
'method': Image.ANTIALIAS,
'centering': (0.5, 0.5),
}
def execute(self, image, query):
return ImageOps.fit(image, (self.x, self.y), self.method, centering=self.centering)
class Blank(Operation):
args = ('x','y','color','mode')
args_defaults = {
'x': None,
'y': None,
'color': None,
'mode': 'RGBA',
}
def execute(self, image, query):
x, y = self.x, self.y
if x is None:
x = image.size[0]
if y is None:
y = image.size[1]
if self.color:
return Image.new(self.mode, (x, y), self.color)
else:
return Image.new(self.mode, (x, y))
class Paste(Operation):
args = ('image','x','y','storage')
def execute(self, image, query):
athor = get_image_object(self.image, self.storage)
x2, y2 = athor.size
x1 = get_coords(image.size[0], athor.size[0], self.x)
y1 = get_coords(image.size[1], athor.size[1], self.y)
box = (
x1,
y1,
x1 + x2,
y1 + y2,
)
# Note that if you paste an "RGBA" image, the alpha band is ignored.
# You can work around this by using the same image as both source image and mask.
image = image.copy()
if athor.mode == 'RGBA':
if image.mode == 'RGBA':
channels = image.split()
alpha = channels[3]
image = Image.merge('RGB', channels[0:3])
athor_channels = athor.split()
athor_alpha = athor_channels[3]
athor = Image.merge('RGB', athor_channels[0:3])
image.paste(athor, box, mask=athor_alpha)
# merge alpha
athor_image_alpha = Image.new('L', image.size, color=0)
athor_image_alpha.paste(athor_alpha, box)
new_alpha = ImageChops.add(alpha, athor_image_alpha)
image = Image.merge('RGBA', image.split() + (new_alpha,))
else:
image.paste(athor, box, mask=athor)
else:
image.paste(athor, box)
return image
class Background(Operation):
args = ('image','x','y','storage')
def execute(self, image, query):
background = Image.new('RGBA', image.size, color=(0,0,0,0))
athor = get_image_object(self.image, self.storage)
x2,y2 = image.size
x1 = get_coords(image.size[0], athor.size[0], self.x)
y1 = get_coords(image.size[1], athor.size[1], self.y)
box = (
x1,
y1,
x1 + x2,
y1 + y2,
)
background.paste(athor, box, mask=athor)
background.paste(image, None, mask=image)
return background
class Convert(Operation):
args = ('mode', 'matrix')
args_defaults = {
'matrix': None,
}
def execute(self, image, query):
if self.matrix:
return image.convert(self.mode, self.matrix)
else:
return image.convert(self.mode)
class GetChannel(Operation):
args = ('channel',)
channel_map = {
'red': 0,
'green': 1,
'blue': 2,
'alpha': 3,
}
def execute(self, image, query):
image = image.convert('RGBA')
alpha = image.split()[self.channel_map[self.channel]]
return Image.merge('RGBA', (alpha, alpha, alpha, alpha))
class ApplyAlpha(GetChannel):
args = ('alphamap',)
def execute(self, image, query):
# TODO: Use putalpha(band)?
image = image.convert('RGBA')
alphamap = get_image_object(self.alphamap).convert('RGBA')
data = image.split()[self.channel_map['red']:self.channel_map['alpha']]
alpha = alphamap.split()[self.channel_map['alpha']]
alpha = alpha.resize(image.size, Image.ANTIALIAS)
return Image.merge('RGBA', data + (alpha,))
class Blend(Operation):
args = ('image','alpha','storage')
channel_map = {
'alpha': 0.5,
}
def execute(self, image, query):
athor = get_image_object(self.image, self.storage)
return Image.blend(image, athor, self.alpha)
class Text(Operation):
args = ('text','x','y','font','size','fill')
args_defaults = {
'size': None,
'fill': None,
}
def execute(self, image, query):
from imagequery import ImageQuery # late import to avoid circular import
image = image.copy()
font = get_font_object(self.font, self.size)
size, offset = ImageQuery.img_textbox(self.text, self.font, self.size)
x = get_coords(image.size[0], size[0], self.x) + offset[0]
y = get_coords(image.size[1], size[1], self.y) + offset[1]
draw = ImageDraw.Draw(image)
text = self.text
# HACK
if Image.VERSION == '1.1.5' and isinstance(text, unicode):
text = text.encode('utf-8')
draw.text((x, y), text, font=font, fill=self.fill)
return image
# TODO: enhance text operations
class TextImage(Operation):
args = ('text', 'font', 'size', 'mode')
args_defaults = {
'size': None,
'fill': None,
}
def execute(self, image, query):
font = get_font_object(self.font, self.size)
font.getmask(self.text)
class FontDefaults(Operation):
args = ('font', 'size', 'fill')
@property
def attrs(self):
return {
'font': self.font,
'size': self.size,
'fill': self.fill,
}
class Composite(Operation):
args = ('image','mask','storage')
def execute(self, image, query):
athor = get_image_object(self.image, self.storage)
mask = get_image_object(self.mask, self.storage)
return Image.composite(image, athor, mask)
class Offset(Operation):
args = ('x','y')
def execute(self, image, query):
return ImageChops.offset(image, self.x, self.y)
class Padding(Operation):
args = ('left','top','right','bottom','color')
def execute(self, image, query):
left, top, right, bottom = self.left, self.top, self.right, self.bottom
color = self.color
if top is None:
top = left
if right is None:
right = left
if bottom is None:
bottom = top
if color is None:
color = (0,0,0,0)
new_width = left + right + image.size[0]
new_height = top + bottom + image.size[1]
new = Image.new('RGBA', (new_width, new_height), color=color)
new.paste(image, (left, top))
return new
class Opacity(Operation):
args = ('opacity',)
def execute(self, image, query):
opacity = int(self.opacity * 255)
background = Image.new('RGBA', image.size, color=(0,0,0,0))
mask = Image.new('RGBA', image.size, color=(0,0,0,opacity))
box = (0,0) + image.size
background.paste(image, box, mask)
return background
class Clip(Operation):
args = ('start','end',)
args_defaults = {
'start': None,
'end': None,
}
def execute(self, image, query):
start = self.start
if start is None:
start = (0, 0)
end = self.end
if end is None:
end = image.size
new = image.crop(self.start + self.end)
new.load() # crop is a lazy operation, see docs
return new
| Python |
# -*- coding: utf-8 -*-
from django.conf.urls.defaults import *
urlpatterns = patterns('imagequery.views',
url(r'^generate/(?P<pk>[0-9]+)?$', 'generate_lazy', name='imagequery_generate_lazy'),
)
| Python |
from django import template
from imagequery import ImageQuery, formats
from imagequery.utils import get_imagequery
from django.db.models.fields.files import ImageFieldFile
from django.utils.encoding import smart_unicode
from imagequery.settings import ALLOW_LAZY_FORMAT, LAZY_FORMAT_DEFAULT
register = template.Library()
def parse_value(value):
try:
if int(value) == float(value):
return int(value)
else:
return float(value)
except (TypeError, ValueError):
return value
def parse_attrs(attrs):
args, kwargs = [], {}
if attrs:
for attr in attrs.split(','):
try:
key, value = attr.split('=', 1)
kwargs[key] = parse_value(value)
except ValueError:
args.append(parse_value(attr))
return args, kwargs
def imagequerify(func):
from functools import wraps
# Template-filters do not work without funcs that _need_ args
# because of some inspect-magic (not) working here
# TODO: Find some way to support optional "attr"
@wraps(func)
def newfunc(image, attr):
try:
image = get_imagequery(image)
except IOError:
return ''
return func(image, attr)
return newfunc
def imagequerify_filter(value):
return get_imagequery(value)
register.filter('imagequerify', imagequerify_filter)
def imagequery_filter(method_name, filter_name=None):
if not filter_name:
filter_name = method_name
def filter(image, attr=None):
args, kwargs = parse_attrs(attr)
return getattr(image, method_name)(*args, **kwargs)
filter = imagequerify(filter)
filter = register.filter(filter_name, filter)
return filter
# register all (/most of) the ImageQuery methods as filters
crop = imagequery_filter('crop')
fit = imagequery_filter('fit')
resize = imagequery_filter('resize')
scale = imagequery_filter('scale')
sharpness = imagequery_filter('sharpness')
blur = imagequery_filter('blur')
truecolor = imagequery_filter('truecolor')
invert = imagequery_filter('invert')
flip = imagequery_filter('flip')
mirror = imagequery_filter('mirror')
grayscale = imagequery_filter('grayscale')
offset = imagequery_filter('offset')
padding = imagequery_filter('padding')
opacity = imagequery_filter('opacity')
shadow = imagequery_filter('shadow')
makeshadow = imagequery_filter('makeshadow')
mimetype = imagequery_filter('mimetype')
width = imagequery_filter('width')
height = imagequery_filter('height')
x = imagequery_filter('x')
y = imagequery_filter('y')
size = imagequery_filter('size')
url = imagequery_filter('url')
query_name = imagequery_filter('query_name')
class ImageFormatNode(template.Node):
def __init__(self, format, image, name, allow_lazy=None):
self.format = format
self.image = image
self.name = name
if allow_lazy is None:
self.allow_lazy = LAZY_FORMAT_DEFAULT and ALLOW_LAZY_FORMAT
else:
self.allow_lazy = allow_lazy and ALLOW_LAZY_FORMAT
def render(self, context):
try:
formatname = self.format.resolve(context)
image = self.image.resolve(context)
except template.VariableDoesNotExist:
return ''
try:
format_cls = formats.get(formatname)
except formats.FormatDoesNotExist:
return ''
try:
imagequery = get_imagequery(image)
except IOError: # handle missing files
return ''
format = format_cls(imagequery)
if self.allow_lazy and not self.name and not format._execute()._exists():
from imagequery.models import LazyFormat
lazy_format = LazyFormat(format=formatname)
lazy_format.query = imagequery
lazy_format.save()
return lazy_format.get_absolute_url()
if self.name:
context[self.name] = format
return ''
else:
try:
return format.url()
except:
return ''
@register.tag
def image_format(parser, token):
"""
Allows you to use predefined Format's for changing your images according to
predefined sets of operations. Format's must be registered for using them
here (using imagequery.formats.register("name", MyFormat).
You can get the resulting Format instance as a context variable.
Examples:
{% image_format "some_format" foo.image %}
{% image_format "some_format" foo.image as var %}
{% image_format "some_format" foo.image lazy %}
{% image_format "some_format" foo.image nolazy %}
This tag does not support storage by design. If you want to use different
storage engines here you have to:
* pass in an ImageQuery instance
* write your own template filter that constructs an ImageQuery instance
(including storage settings)
* pass in an FieldImage
"""
bits = token.split_contents()
tag_name = bits[0]
values = bits[1:]
if len(values) not in (2, 3, 4):
raise template.TemplateSyntaxError(u'%r tag needs two, three or four parameters.' % tag_name)
format = parser.compile_filter(values[0])
image = parser.compile_filter(values[1])
name = None
allow_lazy = None
i = 2
while i < len(values):
if values[i] == 'as':
name = values[i + 1]
i = i + 2
elif values[i] == 'lazy':
allow_lazy = True
i = i + 1
elif values[i] == 'nolazy':
allow_lazy = False
i = i + 2
else:
raise template.TemplateSyntaxError(u'%r tag: parameter must be "as" or "lazy"/"nolazy"' % tag_name)
return ImageFormatNode(format, image, name, allow_lazy)
| Python |
from django.conf import settings
from django.core.files.storage import default_storage as _default_storage,\
get_storage_class
CACHE_DIR = getattr(settings, 'IMAGEQUERY_CACHE_DIR', 'cache')
# can be used to define quality
# IMAGEQUERY_DEFAULT_OPTIONS = {'quality': 92}
DEFAULT_OPTIONS = getattr(settings, 'IMAGEQUERY_DEFAULT_OPTIONS', None)
# storage options
DEFAULT_STORAGE = getattr(settings, 'IMAGEQUERY_DEFAULT_STORAGE', None)
DEFAULT_CACHE_STORAGE = getattr(settings, 'IMAGEQUERY_DEFAULT_CACHE_STORAGE', None)
if DEFAULT_STORAGE:
default_storage = get_storage_class(DEFAULT_STORAGE)
else:
default_storage = _default_storage
if DEFAULT_CACHE_STORAGE:
default_cache_storage = get_storage_class(DEFAULT_CACHE_STORAGE)
else:
# we use the image storage if default_cache_storage is None
default_cache_storage = None
ALLOW_LAZY_FORMAT = getattr(settings, 'IMAGEQUERY_ALLOW_LAZY_FORMAT', False)
LAZY_FORMAT_DEFAULT = getattr(settings, 'IMAGEQUERY_LAZY_FORMAT_DEFAULT', False)
LAZY_FORMAT_CLEANUP_TIME = getattr(settings, 'IMAGEQUERY_LAZY_FORMAT_CLEANUP_TIME', 86400) # one day
| Python |
try:
from PIL import Image
from PIL import ImageFile
from PIL import ImageFont
except ImportError:
import Image
import ImageFile
import ImageFont
from django.core.cache import cache
from django.core.files.base import File
from imagequery.settings import default_storage
def get_imagequery(value):
from imagequery import ImageQuery # late import to avoid circular import
if isinstance(value, ImageQuery):
return value
# value must be the path to an image or an image field (model attr)
return ImageQuery(value)
def _get_image_object(value, storage=default_storage):
from imagequery import ImageQuery # late import to avoid circular import
if isinstance(value, (ImageFile.ImageFile, Image.Image)):
return value
if isinstance(value, ImageQuery):
return value.raw()
if isinstance(value, File):
value.open('rb')
return Image.open(value)
return Image.open(storage.open(value, 'rb'))
def get_image_object(value, storage=default_storage):
image = _get_image_object(value, storage)
# PIL Workaround:
# We avoid lazy loading here as ImageQuery already is lazy enough.
# In addition PIL does not always check if image is loaded, so not
# loading it here might break some code (for example ImageQuery.paste)
if not getattr(image, 'im', True):
try:
image.load()
except AttributeError:
pass
return image
def get_font_object(value, size=None):
if isinstance(value, (ImageFont.ImageFont, ImageFont.FreeTypeFont)):
return value
if value[-4:].lower() in ('.ttf', '.otf'):
return ImageFont.truetype(value, size)
return ImageFont.load(value)
def get_coords(first, second, align):
if align in ('left', 'top'):
return 0
if align in ('center', 'middle'):
return (first / 2) - (second / 2)
if align in ('right', 'bottom'):
return first - second
return align
# TODO: Keep this?
# TODO: Add storage support
# TODO: Move to equal_height.py?
def equal_height(images, maxwidth=None):
""" Allows you to pass in multiple images, which all get resized to
the same height while allowing you to defina a maximum width.
The maximum height is calculated by resizing every image to the maximum
width and comparing all resulting heights. maxheight gets to be
min(heights). Because of the double-resize involved here the function
caches the heights. But there is room for improvement. """
from imagequery import ImageQuery # late import to avoid circular import
minheight = None # infinity
all_values = ':'.join(images.values())
for i, value in images.items():
if not value:
continue
try:
cache_key = 'imagequery_equal_height_%s_%s_%d' % (all_values, value, maxwidth)
height = cache.get(cache_key, None)
if height is None:
height = ImageQuery(value).resize(x=maxwidth).height()
cache.set(cache_key, height, 604800) # 7 days
if minheight is None or height < minheight:
minheight = height
except IOError:
pass
result = {}
for i, value in images.items():
try:
result[i] = ImageQuery(value).scale(x=maxwidth, y=minheight)
except IOError:
result[i] = None
return result
| Python |
from django.http import HttpResponseRedirect, Http404
from django.core.exceptions import ImproperlyConfigured
def generate_lazy(request, pk):
try:
from imagequery.models import LazyFormat
except ImportError:
raise ImproperlyConfigured('You have to set "IMAGEQUERY_ALLOW_LAZY_FORMAT = True" in order to use this view')
LazyFormat.objects.cleanup()
try:
lazy_format = LazyFormat.objects.get(pk=pk)
except LazyFormat.DoesNotExist:
raise Http404()
return HttpResponseRedirect(lazy_format.generate_image_url())
| Python |
from imagequery.query import RawImageQuery, NewImageQuery, ImageQuery
from imagequery.formats import Format, register as register_format
from imagequery.operations import Operation, CommandOperation
| Python |
# -*- coding: utf-8 -*-
from django.contrib.auth.models import User
from django import forms
from django.utils.translation import ugettext_lazy as _
attrs_dict = {'class': 'required'}
class RegistrationForm(forms.Form):
"""
Form for registering a new user account.
Validates that the requested username is not already in use, and
requires the password to be entered twice to catch typos.
Subclasses should feel free to add any additional validation they
need, but should avoid defining a ``save()`` method -- the actual
saving of collected user data is delegated to the active
registration backend.
"""
username = forms.RegexField(regex=r'^\w+$', max_length=30, widget=forms.TextInput(attrs=attrs_dict), label=_("Benutzername"), error_messages={'invalid': _("Nur Buchstaben, Zahlen und Unterstriche erlaubt.")})
email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=75)), label=_("E-Mail"))
password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), label=_("Passwort"))
password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), label=_("Password (Wiederholung)"))
def clean_username(self):
"""
Validate that the username is alphanumeric and is not already
in use.
"""
try:
user = User.objects.get(username__iexact=self.cleaned_data['username'])
except User.DoesNotExist:
return self.cleaned_data['username']
raise forms.ValidationError(_("Es existiert bereits ein Benutzer mit diesem Namen."))
def clean(self):
"""
Verifiy that the values entered into the two password fields
match. Note that an error here will end up in
``non_field_errors()`` because it doesn't apply to a single
field.
"""
if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
if self.cleaned_data['password1'] != self.cleaned_data['password2']:
raise forms.ValidationError(_("Die eingegebenen Passwörter stimmen nicht überein!"))
return self.cleaned_data
class RegistrationFormTermsOfService(RegistrationForm):
"""
Subclass of ``RegistrationForm`` which adds a required checkbox
for agreeing to a site's Terms of Service.
"""
tos = forms.BooleanField(widget=forms.CheckboxInput(attrs=attrs_dict), label=_(u'Ich habe die Nutzungsbedingungen gelesen und akzeptiere sie.'), error_messages={'required': _("Du musst den Nutzungsbedingungen zustimmen")})
class RegistrationFormUniqueEmail(RegistrationForm):
"""
Subclass of ``RegistrationForm`` which enforces uniqueness of
email addresses.
"""
def clean_email(self):
"""
Validate that the supplied email address is unique for the
site.
"""
if User.objects.filter(email__iexact=self.cleaned_data['email']):
raise forms.ValidationError(_("Diese E-Mail Adresse wird bereits verwendet, bitte nimm eine andere"))
return self.cleaned_data['email']
class RegistrationFormNoFreeEmail(RegistrationForm):
"""
Subclass of ``RegistrationForm`` which disallows registration with
email addresses from popular free webmail services; moderately
useful for preventing automated spam registrations.
To change the list of banned domains, subclass this form and
override the attribute ``bad_domains``.
"""
bad_domains = ['aim.com', 'aol.com', 'email.com', 'gmail.com',
'googlemail.com', 'hotmail.com', 'hushmail.com',
'msn.com', 'mail.ru', 'mailinator.com', 'live.com',
'yahoo.com']
def clean_email(self):
"""
Check the supplied email address against a list of known free
webmail domains.
"""
email_domain = self.cleaned_data['email'].split('@')[1]
if email_domain in self.bad_domains:
raise forms.ValidationError(_("Registrierung über FreeMail Adressen ist verboten, bitte benutze eine andere."))
return self.cleaned_data['email']
| Python |
# -*- coding: utf-8 -*-
import datetime
import random
import re
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
from django.db import transaction
from django.db.models.signals import post_save
from django.template.loader import render_to_string
from django.utils.hashcompat import sha_constructor
from django.utils.translation import ugettext_lazy as _
from django_model_utils.models import StatMixin, PageMixin
SHA1_RE = re.compile('^[a-f0-9]{40}$')
class RegistrationManager(models.Manager):
"""
Custom manager for the ``RegistrationProfile`` model.
The methods defined here provide shortcuts for account creation
and activation (including generation and emailing of activation
keys), and for cleaning out expired inactive accounts.
"""
def activate_user(self, activation_key):
"""
Validate an activation key and activate the corresponding
``User`` if valid.
If the key is valid and has not expired, return the ``User``
after activating.
If the key is not valid or has expired, return ``False``.
If the key is valid but the ``User`` is already active,
return ``False``.
To prevent reactivation of an account which has been
deactivated by site administrators, the activation key is
reset to the string constant ``RegistrationProfile.ACTIVATED``
after successful activation.
"""
# Make sure the key we're trying conforms to the pattern of a
# SHA1 hash; if it doesn't, no point trying to look it up in
# the database.
if SHA1_RE.search(activation_key):
try:
profile = self.get(activation_key=activation_key)
except self.model.DoesNotExist:
return False
if not profile.activation_key_expired():
user = profile.user
user.is_active = True
user.save()
profile.activation_key = self.model.ACTIVATED
profile.save()
return user
return False
def create_inactive_user(self, username, email, password,
site, send_email=True):
"""
Create a new, inactive ``User``, generate a
``RegistrationProfile`` and email its activation key to the
``User``, returning the new ``User``.
By default, an activation email will be sent to the new
user. To disable this, pass ``send_email=False``.
"""
new_user = User.objects.create_user(username, email, password)
new_user.is_active = False
new_user.save()
registration_profile = self.create_profile(new_user)
if send_email:
registration_profile.send_activation_email(site)
return new_user
create_inactive_user = transaction.commit_on_success(create_inactive_user)
def create_profile(self, user):
"""
Create a ``RegistrationProfile`` for a given
``User``, and return the ``RegistrationProfile``.
The activation key for the ``RegistrationProfile`` will be a
SHA1 hash, generated from a combination of the ``User``'s
username and a random salt.
"""
salt = sha_constructor(str(random.random())).hexdigest()[:5]
username = user.username
if isinstance(username, unicode):
username = username.encode('utf-8')
activation_key = sha_constructor(salt+username).hexdigest()
return self.create(user=user,
activation_key=activation_key)
def delete_expired_users(self):
"""
Remove expired instances of ``RegistrationProfile`` and their
associated ``User``s.
Accounts to be deleted are identified by searching for
instances of ``RegistrationProfile`` with expired activation
keys, and then checking to see if their associated ``User``
instances have the field ``is_active`` set to ``False``; any
``User`` who is both inactive and has an expired activation
key will be deleted.
It is recommended that this method be executed regularly as
part of your routine site maintenance; this application
provides a custom management command which will call this
method, accessible as ``manage.py cleanupregistration``.
Regularly clearing out accounts which have never been
activated serves two useful purposes:
1. It alleviates the ocasional need to reset a
``RegistrationProfile`` and/or re-send an activation email
when a user does not receive or does not act upon the
initial activation email; since the account will be
deleted, the user will be able to simply re-register and
receive a new activation key.
2. It prevents the possibility of a malicious user registering
one or more accounts and never activating them (thus
denying the use of those usernames to anyone else); since
those accounts will be deleted, the usernames will become
available for use again.
If you have a troublesome ``User`` and wish to disable their
account while keeping it in the database, simply delete the
associated ``RegistrationProfile``; an inactive ``User`` which
does not have an associated ``RegistrationProfile`` will not
be deleted.
"""
for profile in self.all():
if profile.activation_key_expired():
user = profile.user
if not user.is_active:
user.delete()
class RegistrationProfile(models.Model):
"""
A simple profile which stores an activation key for use during
user account registration.
Generally, you will not want to interact directly with instances
of this model; the provided manager includes methods
for creating and activating new accounts, as well as for cleaning
out accounts which have never been activated.
While it is possible to use this model as the value of the
``AUTH_PROFILE_MODULE`` setting, it's not recommended that you do
so. This model's sole purpose is to store data temporarily during
account registration and activation.
"""
ACTIVATED = u"Bereits aktiviert"
user = models.ForeignKey(User, unique=True, verbose_name=_('Benutzer'))
activation_key = models.CharField(_('Aktivierungsschlüssel'), max_length=40)
objects = RegistrationManager()
class Meta:
verbose_name = _('Registrierungsprofil')
verbose_name_plural = _('Registrierungsprofile')
def __unicode__(self):
return u"Registrierungsinformation für %s" % self.user
def activation_key_expired(self):
"""
Determine whether this ``RegistrationProfile``'s activation
key has expired, returning a boolean -- ``True`` if the key
has expired.
Key expiration is determined by a two-step process:
1. If the user has already activated, the key will have been
reset to the string constant ``ACTIVATED``. Re-activating
is not permitted, and so this method returns ``True`` in
this case.
2. Otherwise, the date the user signed up is incremented by
the number of days specified in the setting
``ACCOUNT_ACTIVATION_DAYS`` (which should be the number of
days after signup during which a user is allowed to
activate their account); if the result is less than or
equal to the current date, the key has expired and this
method returns ``True``.
"""
expiration_date = datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS)
return self.activation_key == self.ACTIVATED or \
(self.user.date_joined + expiration_date <= datetime.datetime.now())
activation_key_expired.boolean = True
def send_activation_email(self, site):
"""
Send an activation email to the user associated with this
``RegistrationProfile``.
The activation email will make use of two templates:
``registration/activation_email_subject.txt``
This template will be used for the subject line of the
email. Because it is used as the subject line of an email,
this template's output **must** be only a single line of
text; output longer than one line will be forcibly joined
into only a single line.
``registration/activation_email.txt``
This template will be used for the body of the email.
These templates will each receive the following context
variables:
``activation_key``
The activation key for the new account.
``expiration_days``
The number of days remaining during which the account may
be activated.
``site``
An object representing the site on which the user
registered; depending on whether ``django.contrib.sites``
is installed, this may be an instance of either
``django.contrib.sites.models.Site`` (if the sites
application is installed) or
``django.contrib.sites.models.RequestSite`` (if
not). Consult the documentation for the Django sites
framework for details regarding these objects' interfaces.
"""
ctx_dict = {'activation_key': self.activation_key,
'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
'site': site}
subject = render_to_string('account/activation_email_subject.txt',
ctx_dict)
# Email subject *must not* contain newlines
subject = ''.join(subject.splitlines())
message = render_to_string('account/activation_email.txt',
ctx_dict)
self.user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
class UserProfile(StatMixin, PageMixin, models.Model):
'''
Extends the Django user model with some more fields to store in database
After each user has been registered, a user profile model will be
created.
'''
user = models.ForeignKey(User, unique=True, verbose_name=_('Benutzer'))
description = models.TextField(verbose_name=_('Benutzerbeschreibung'), null=True, blank=True)
homepage = models.URLField(max_length=200, verbose_name=_('Homepage'), null=True, blank=True)
skype = models.CharField(max_length=120, verbose_name=_('Skype'), null=True, blank=True)
city = models.CharField(max_length=150, verbose_name=_('Wohnort'), null=True, blank=True)
avatar = models.ImageField(max_length=180, upload_to='account/avatar', verbose_name=_('Benutzerbild'), null=True, blank=True)
class Meta:
verbose_name = _('Benutzerprofil')
verbose_name_plural = _('Benutzerprofile')
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
import gironimo.account.image_formats
| Python |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
| Python |
from django.dispatch import Signal
# A new user has registered.
user_registered = Signal(providing_args=["user", "request"])
# A user has activated his or her account.
user_activated = Signal(providing_args=["user", "request"])
| Python |
"""
Backwards-compatible URLconf for existing django-registration
installs; this allows the standard ``include('registration.urls')`` to
continue working, but that usage is deprecated and will be removed for
django-registration 1.0. For new installs, use
``include('registration.backends.default.urls')``.
"""
import warnings
warnings.warn("include('gironimo.account.urls') is deprecated; use include('gironimo.account.backends.default.urls') instead.",
PendingDeprecationWarning)
from gironimo.account.backends.default.urls import *
| Python |
from django.contrib import admin
from django.contrib.sites.models import RequestSite
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _
from gironimo.account.models import RegistrationProfile, UserProfile
class RegistrationAdmin(admin.ModelAdmin):
actions = ['activate_users', 'resend_activation_email']
list_display = ('user', 'activation_key_expired')
raw_id_fields = ['user']
search_fields = ('user__username', 'user__first_name', 'user__last_name')
def activate_users(self, request, queryset):
for profile in queryset:
RegistrationProfile.objects.activate_user(profile.activation_key)
activate_users.short_description = _('Benutzer aktivieren')
def resend_activation_email(self, request, queryset):
if Site._meta.installed:
site = Site.objects.get_current()
else:
site = RequestSite(request)
for profile in queryset:
if not profile.activation_key_expired():
profile.send_activation_email(site)
resend_activation_email.short_description = _('Aktivierungsmails nochmals senden')
class UserProfileAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['user',]}),
(_('Benutzerinformationen'), {'fields': ['description', 'homepage', 'skype', 'city', 'avatar',]}),
(_('HTML'), {'fields': ['html_title', 'html_description', 'html_keywords',], 'classes': ['collapse']}),
]
list_display = ('user', 'created', 'homepage', 'city',)
search_fields = ['user', 'city',]
list_filter = ['city', 'created',]
admin.site.register(RegistrationProfile, RegistrationAdmin)
admin.site.register(UserProfile, UserProfileAdmin)
| Python |
from gironimo.imagequery import Format, register_format
class AccountAvatarFormat(Format):
'''
Crops the user avatar into 50x50 px
'''
def execute(self, query):
return query.fit(50, 50).image_format('JPEG').query_name('account_avatar')
register_format('account_avatar', AccountAvatarFormat)
| Python |
from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
from gironimo.account.views import activate, register
urlpatterns = patterns('',
url(r'^register/$', register, {'backend': 'gironimo.account.backends.simple.SimpleBackend'}, name='registration_register'),
url(r'^register/closed/$', direct_to_template, {'template': 'account/registration_closed.html'}, name='registration_disallowed'),
(r'', include('gironimo.account.auth_urls')),
)
| Python |
from django.conf import settings
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django.contrib.auth.models import User
from gironimo.account import signals
from gironimo.account.forms import RegistrationForm
class SimpleBackend(object):
"""
A registration backend which implements the simplest possible
workflow: a user supplies a username, email address and password
(the bare minimum for a useful account), and is immediately signed
up and logged in.
"""
def register(self, request, **kwargs):
"""
Create and immediately log in a new user.
"""
username, email, password = kwargs['username'], kwargs['email'], kwargs['password1']
User.objects.create_user(username, email, password)
# authenticate() always has to be called before login(), and
# will return the user we just created.
new_user = authenticate(username=username, password=password)
login(request, new_user)
signals.user_registered.send(sender=self.__class__,
user=new_user,
request=request)
return new_user
def activate(self, **kwargs):
raise NotImplementedError
def registration_allowed(self, request):
"""
Indicate whether account registration is currently permitted,
based on the value of the setting ``REGISTRATION_OPEN``. This
is determined as follows:
* If ``REGISTRATION_OPEN`` is not specified in settings, or is
set to ``True``, registration is permitted.
* If ``REGISTRATION_OPEN`` is both specified and set to
``False``, registration is not permitted.
"""
return getattr(settings, 'REGISTRATION_OPEN', True)
def get_form_class(self, request):
return RegistrationForm
def post_registration_redirect(self, request, user):
"""
After registration, redirect to the user's account page.
"""
return (user.get_absolute_url(), (), {})
def post_activation_redirect(self, request, user):
raise NotImplementedError
| Python |
from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
from gironimo.account.views import activate, register
urlpatterns = patterns('',
url(r'^activate/complete/$', direct_to_template, {'template': 'account/activation_complete.html'}, name='account_activation_complete'),
url(r'^activate/(?P<activation_key>\w+)/$', activate, {'backend': 'gironimo.account.backends.default.DefaultBackend'}, name='account_activate'),
url(r'^register/$', register, {'backend': 'gironimo.account.backends.default.DefaultBackend'}, name='account_register'),
url(r'^register/complete/$', direct_to_template, {'template': 'account/registration_complete.html'}, name='account_complete'),
url(r'^register/closed/$', direct_to_template, {'template': 'account/registration_closed.html'}, name='account_disallowed'),
url(r'^profile/edit/$', 'gironimo.account.views.profile_edit', name='account_profile_edit'),
url(r'^profile/(?P<slug>[a-z0-9_-]+)/$', 'gironimo.account.views.show_profile', name='account_show_profile'),
url(r'^profile/$', 'gironimo.account.views.profile', name='account_profile'),
(r'', include('gironimo.account.auth_urls')),
)
| Python |
from django.conf import settings
from django.contrib.sites.models import RequestSite
from django.contrib.sites.models import Site
from gironimo.account import signals
from gironimo.account.forms import RegistrationForm
from gironimo.account.models import RegistrationProfile
class DefaultBackend(object):
"""
A registration backend which follows a simple workflow:
1. User signs up, inactive account is created.
2. Email is sent to user with activation link.
3. User clicks activation link, account is now active.
Using this backend requires that
* ``registration`` be listed in the ``INSTALLED_APPS`` setting
(since this backend makes use of models defined in this
application).
* The setting ``ACCOUNT_ACTIVATION_DAYS`` be supplied, specifying
(as an integer) the number of days from registration during
which a user may activate their account (after that period
expires, activation will be disallowed).
* The creation of the templates
``registration/activation_email_subject.txt`` and
``registration/activation_email.txt``, which will be used for
the activation email. See the notes for this backends
``register`` method for details regarding these templates.
Additionally, registration can be temporarily closed by adding the
setting ``REGISTRATION_OPEN`` and setting it to
``False``. Omitting this setting, or setting it to ``True``, will
be interpreted as meaning that registration is currently open and
permitted.
Internally, this is accomplished via storing an activation key in
an instance of ``registration.models.RegistrationProfile``. See
that model and its custom manager for full documentation of its
fields and supported operations.
"""
def register(self, request, **kwargs):
"""
Given a username, email address and password, register a new
user account, which will initially be inactive.
Along with the new ``User`` object, a new
``registration.models.RegistrationProfile`` will be created,
tied to that ``User``, containing the activation key which
will be used for this account.
An email will be sent to the supplied email address; this
email should contain an activation link. The email will be
rendered using two templates. See the documentation for
``RegistrationProfile.send_activation_email()`` for
information about these templates and the contexts provided to
them.
After the ``User`` and ``RegistrationProfile`` are created and
the activation email is sent, the signal
``registration.signals.user_registered`` will be sent, with
the new ``User`` as the keyword argument ``user`` and the
class of this backend as the sender.
"""
username, email, password = kwargs['username'], kwargs['email'], kwargs['password1']
if Site._meta.installed:
site = Site.objects.get_current()
else:
site = RequestSite(request)
new_user = RegistrationProfile.objects.create_inactive_user(username, email,
password, site)
signals.user_registered.send(sender=self.__class__,
user=new_user,
request=request)
return new_user
def activate(self, request, activation_key):
"""
Given an an activation key, look up and activate the user
account corresponding to that key (if possible).
After successful activation, the signal
``registration.signals.user_activated`` will be sent, with the
newly activated ``User`` as the keyword argument ``user`` and
the class of this backend as the sender.
"""
activated = RegistrationProfile.objects.activate_user(activation_key)
if activated:
signals.user_activated.send(sender=self.__class__,
user=activated,
request=request)
return activated
def registration_allowed(self, request):
"""
Indicate whether account registration is currently permitted,
based on the value of the setting ``REGISTRATION_OPEN``. This
is determined as follows:
* If ``REGISTRATION_OPEN`` is not specified in settings, or is
set to ``True``, registration is permitted.
* If ``REGISTRATION_OPEN`` is both specified and set to
``False``, registration is not permitted.
"""
return getattr(settings, 'REGISTRATION_OPEN', True)
def get_form_class(self, request):
"""
Return the default form class used for user registration.
"""
return RegistrationForm
def post_registration_redirect(self, request, user):
"""
Return the name of the URL to redirect to after successful
user registration.
"""
return ('account_complete', (), {})
def post_activation_redirect(self, request, user):
"""
Return the name of the URL to redirect to after successful
account activation.
"""
return ('account_activation_complete', (), {})
| Python |
from django.core.exceptions import ImproperlyConfigured
# Python 2.7 has an importlib with import_module; for older Pythons,
# Django's bundled copy provides it.
try:
from importlib import import_module
except ImportError:
from django.utils.importlib import import_module
def get_backend(path):
"""
Return an instance of a registration backend, given the dotted
Python import path (as a string) to the backend class.
If the backend cannot be located (e.g., because no such module
exists, or because the module does not contain a class of the
appropriate name), ``django.core.exceptions.ImproperlyConfigured``
is raised.
"""
i = path.rfind('.')
module, attr = path[:i], path[i+1:]
try:
mod = import_module(module)
except ImportError, e:
raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e))
try:
backend_class = getattr(mod, attr)
except AttributeError:
raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr))
return backend_class()
| Python |
"""
Views which allow users to create and activate accounts.
"""
from django.shortcuts import redirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.forms.models import modelformset_factory, inlineformset_factory
from gironimo.account.backends import get_backend
from gironimo.account.models import UserProfile
def activate(request, backend,
template_name='account/activate.html',
success_url=None, extra_context=None, **kwargs):
"""
Activate a user's account.
The actual activation of the account will be delegated to the
backend specified by the ``backend`` keyword argument (see below);
the backend's ``activate()`` method will be called, passing any
keyword arguments captured from the URL, and will be assumed to
return a ``User`` if activation was successful, or a value which
evaluates to ``False`` in boolean context if not.
Upon successful activation, the backend's
``post_activation_redirect()`` method will be called, passing the
``HttpRequest`` and the activated ``User`` to determine the URL to
redirect the user to. To override this, pass the argument
``success_url`` (see below).
On unsuccessful activation, will render the template
``registration/activate.html`` to display an error message; to
override thise, pass the argument ``template_name`` (see below).
**Arguments**
``backend``
The dotted Python import path to the backend class to
use. Required.
``extra_context``
A dictionary of variables to add to the template context. Any
callable object in this dictionary will be called to produce
the end result which appears in the context. Optional.
``success_url``
The name of a URL pattern to redirect to on successful
acivation. This is optional; if not specified, this will be
obtained by calling the backend's
``post_activation_redirect()`` method.
``template_name``
A custom template to use. This is optional; if not specified,
this will default to ``registration/activate.html``.
``\*\*kwargs``
Any keyword arguments captured from the URL, such as an
activation key, which will be passed to the backend's
``activate()`` method.
**Context:**
The context will be populated from the keyword arguments captured
in the URL, and any extra variables supplied in the
``extra_context`` argument (see above).
**Template:**
registration/activate.html or ``template_name`` keyword argument.
"""
backend = get_backend(backend)
account = backend.activate(request, **kwargs)
if account:
if success_url is None:
to, args, kwargs = backend.post_activation_redirect(request, account)
return redirect(to, *args, **kwargs)
else:
return redirect(success_url)
if extra_context is None:
extra_context = {}
context = RequestContext(request)
for key, value in extra_context.items():
context[key] = callable(value) and value() or value
return render_to_response(template_name,
kwargs,
context_instance=context)
def register(request, backend, success_url=None, form_class=None,
disallowed_url='registration_disallowed',
template_name='account/registration_form.html',
extra_context=None):
"""
Allow a new user to register an account.
The actual registration of the account will be delegated to the
backend specified by the ``backend`` keyword argument (see below);
it will be used as follows:
1. The backend's ``registration_allowed()`` method will be called,
passing the ``HttpRequest``, to determine whether registration
of an account is to be allowed; if not, a redirect is issued to
the view corresponding to the named URL pattern
``registration_disallowed``. To override this, see the list of
optional arguments for this view (below).
2. The form to use for account registration will be obtained by
calling the backend's ``get_form_class()`` method, passing the
``HttpRequest``. To override this, see the list of optional
arguments for this view (below).
3. If valid, the form's ``cleaned_data`` will be passed (as
keyword arguments, and along with the ``HttpRequest``) to the
backend's ``register()`` method, which should return the new
``User`` object.
4. Upon successful registration, the backend's
``post_registration_redirect()`` method will be called, passing
the ``HttpRequest`` and the new ``User``, to determine the URL
to redirect the user to. To override this, see the list of
optional arguments for this view (below).
**Required arguments**
None.
**Optional arguments**
``backend``
The dotted Python import path to the backend class to use.
``disallowed_url``
URL to redirect to if registration is not permitted for the
current ``HttpRequest``. Must be a value which can legally be
passed to ``django.shortcuts.redirect``. If not supplied, this
will be whatever URL corresponds to the named URL pattern
``registration_disallowed``.
``form_class``
The form class to use for registration. If not supplied, this
will be retrieved from the registration backend.
``extra_context``
A dictionary of variables to add to the template context. Any
callable object in this dictionary will be called to produce
the end result which appears in the context.
``success_url``
URL to redirect to after successful registration. Must be a
value which can legally be passed to
``django.shortcuts.redirect``. If not supplied, this will be
retrieved from the registration backend.
``template_name``
A custom template to use. If not supplied, this will default
to ``registration/registration_form.html``.
**Context:**
``form``
The registration form.
Any extra variables supplied in the ``extra_context`` argument
(see above).
**Template:**
registration/registration_form.html or ``template_name`` keyword
argument.
"""
backend = get_backend(backend)
if not backend.registration_allowed(request):
return redirect(disallowed_url)
if form_class is None:
form_class = backend.get_form_class(request)
if request.method == 'POST':
form = form_class(data=request.POST, files=request.FILES)
if form.is_valid():
new_user = backend.register(request, **form.cleaned_data)
if success_url is None:
to, args, kwargs = backend.post_registration_redirect(request, new_user)
return redirect(to, *args, **kwargs)
else:
return redirect(success_url)
else:
form = form_class()
if extra_context is None:
extra_context = {}
context = RequestContext(request)
for key, value in extra_context.items():
context[key] = callable(value) and value() or value
return render_to_response(template_name,
{'form': form},
context_instance=context)
def profile(request):
'''
Shows the current profile of the logged in user
'''
return render_to_response('account/profile.html', {
}, context_instance=RequestContext(request))
@login_required
def profile_edit(request):
'''
Edits profile information
'''
UserProfileFormset = inlineformset_factory(User, UserProfile, extra=0, exclude=('html_title','html_description','html_keywords',))
user = request.user
if request.method == 'POST':
formset = UserProfileFormset(request.POST, request.FILES, instance=user)
if formset.is_valid():
formset.save()
return HttpResponseRedirect(reverse('account_profile', kwargs={'slug':slug}))
else:
formset = UserProfileFormset(instance=user)
return render_to_response('account/profile_edit.html', {
'formset': formset}, context_instance=RequestContext(request))
def show_profile(request, slug):
'''
Shows an explicit user profile
'''
user = User.objects.get(username=slug)
user_profile = user.get_profile()
return render_to_response('account/profile_show.html', {
'user_profile': user_profile, 'user': user}, context_instance=RequestContext(request))
| Python |
VERSION = (0, 8, 0, 'alpha', 1)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
if VERSION[3] != 'final':
version = "%s %s" % (version, VERSION[3])
if VERSION[4] != 0:
version = '%s %s' % (version, VERSION[4])
return version
| Python |
from django.conf.urls.defaults import *
from django.contrib.auth import views as auth_views
urlpatterns = patterns('',
url(r'^login/$', auth_views.login, {'template_name': 'account/login.html'}, name='auth_login'),
url(r'^logout/$', auth_views.logout, {'template_name': 'account/logout.html'}, name='auth_logout'),
url(r'^password/change/$', auth_views.password_change, {'template_name': 'account/password_change_form.html'}, name='auth_password_change'),
url(r'^password/change/done/$', auth_views.password_change_done, {'template_name': 'account/password_change_done.html'}, name='auth_password_change_done'),
url(r'^password/reset/$', auth_views.password_reset, {'template_name': 'account/password_reset_form.html'}, name='auth_password_reset'),
url(r'^password/reset/confirm/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$', auth_views.password_reset_confirm, {'template_name': 'account/password_reset_confirm.html'}, name='auth_password_reset_confirm'),
url(r'^password/reset/complete/$', auth_views.password_reset_complete, {'template_name': 'account/password_reset_complete.html'} ,name='auth_password_reset_complete'),
url(r'^password/reset/done/$', auth_views.password_reset_done, {'template_name': 'account/password_reset_done.html'} ,name='auth_password_reset_done'),
)
| Python |
#-*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from django_model_utils.models import StatMixin, PageMixin, StatusMixin, ClonableMixin, StatClonableMixin
from tagging.fields import TagField
from tagging.models import Tag
from gironimo.category.models import Category
class Post(StatMixin, models.Model):
user = models.ForeignKey(User, related_name='posts')
slug = models.SlugField(max_length=200, unique=True, null=True)
def _cleanup_states(self):
try:
del self._live_revision
except AttributeError:
pass
def add_revision(self, revision=None, base=None):
self._cleanup_states()
if revision is None:
if base is None:
try:
base = self.get_live_revision()
except PostRevision.DoesNotExist:
try:
base = self.get_latest_revision()
except PostRevision.DoesNotExist:
raise RuntimeError('Um die erste (initiale) Revision zu erstellen muss ein das Revisionsargument übergeben werden.')
return base.clone()
elif base is None:
if self.slug is None and not self.has_revisions():
from django.template.defaultfilters import slugify
# Generate slug
slug = slugify(revision.title)
i = 2
while Post.objects.filter(slug=slug):
slug = slugify(revision.title) + '-' + str(i)
i += 1
self.slug = slug
self.save()
revision.entry = self
revision.save()
return revision
else:
raise RuntimeError('Entweder Revision angeben oder Base, aber nicht beides!')
def has_revisions(self):
return self.revisions.exists()
def get_latest_revision(self, **kwargs):
try:
return self.revisions.filter(**kwargs).order_by('-created')[0]
except AttributeError:
raise PostRevision.DoesNotExist()
def get_live_revision(self, **kwargs):
try:
return self._live_revision
except AttributeError:
self._live_revision = self.revisions.filter(**kwargs).get(status__gte.PostRevision.STATUS_LIVE)
return self._live_revision
def has_live_revision(self, **kwargs):
try:
self.get_live_revision()
return True
except PostRevision.DoesNotExist:
return False
def get_frontend_edit_revision(self):
try:
live_revision = self.get_live_revision()
except PostRevision.DoesNotExist:
live_revision = None
draft_revisions = self.revisions.draft()
if live_revision:
draft_revisions = draft_revisions.filter(created__gte = live_revision.created)
try:
return draft_revisions.order_by('-created')[0]
except IndexError:
pass
if live_revision:
return self.add_revision(base=live_revision)
else:
return self.add_revision()
def publish_revision(self, revision):
self._cleanup_states()
self.revisions.exclude(pk=revision.pk).filter(status=PostRevision.STATUS_LIVE).update(status=PostRevision.STATUS_ARCHIVE)
self.revisions.filter(pk=revision.pk).update(status=PostRevision.STATUS_LIVE)
revision.status = PostRevision.STATUS_LIVE
return revision
def __unicode__(self):
return self.slug
@models.permalink
def get_absolute_url(self):
return 'blog_detail', (), {'slug': self.slug}
class Meta:
verbose_name = _(u'Blogeintrag')
verbose_name_plural = _(u'Blogeinträge')
class PostRevisionCloneableMixin(StatClonableMixin):
def _clone_prepare(self, duplicate):
super(PostRevisionCloneableMixin, self)._clone_prepare(duplicate)
duplicate.status = self.STATUS_DRAFT
class PostRevision(StatMixin, StatusMixin, PageMixin, PostRevisionCloneableMixin, models.Model):
post = models.ForeignKey(Post, related_name='revisions')
category = models.ForeignKey(Category)
title = models.CharField(max_length=120, verbose_name=_('Titel'))
content = models.TextField(verbose_name=_('Inhalt'))
pic = models.ImageField(max_length=200, upload_to='blog/logo', verbose_name=_('Artikelbild'), blank=True, null=True)
tags = TagField()
def set_tags(self, tags):
Tag.objects.update_tags(self, tags)
def get_tags(self, tags):
return Tag.objects.get_for_object(self)
def publish(self):
self.post.publish_revision(self)
def has_previous_revision(self):
try:
self.get_previous_revision()
return True
except PostRevision.DoesNotExist:
return False
def has_next_revision(self):
try:
self.get_next_revision()
return True
except PostRevision.DoesNotExist:
return False
def get_previous_revision(self):
try:
return PostRevision.objects.filter(post=self.post, created__lt=self.created).order_by('-created')[0]
except IndexError:
raise PostRevision.DoesNotExist()
def get_next_revision(self):
try:
return PostRevision.objects.filter(post=self.post, created__gt=self.created).order_by('created')[0]
except IndexError:
raise PostRevision.DoesNotExist()
def __unicode__(self):
return self.title
class Meta:
verbose_name = _(u'Blogeintrag Revision')
verbose_name_plural = _('Blogeintrag Revisionen')
| Python |
#-*- coding: utf-8 -*-
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from gironimo.blog.models import Post, PostRevision
class PostRevisionInline(admin.TabularInline):
model = PostRevision
extra = 1
class PostAdmin(admin.ModelAdmin):
date_hierarchy = 'created'
list_display = ('user', 'slug', 'created')
inlines = (PostRevisionInline,)
class PostRevisionAdmin(admin.ModelAdmin):
date_hierarchy = 'created'
list_filter = ('status',)
list_display = ('get_revision_title', 'created', 'status',)
list_per_page = 20
ordering = ['-created', '-status',]
search_fields = ['title',]
actions = [
'publish_revision',
]
fieldsets = [
(_('Eintrag'), {'fields': ['status', 'title', 'content', 'category', 'pic', 'tags',]}),
(_('HTML'), {'fields': ['html_title', 'html_description', 'html_keywords',], 'classes': ['collapse']}),
]
def get_revision_title(self, obj):
return '%s - %d.%d.%d' % (obj.title, obj.created.day, obj.created.month, obj.created.year)
get_revision_title.short_description = _('Revisiontitel')
def publish_revision(self, request, queryset):
for obj in queryset:
obj.publish()
self.message_user(request, "%d Revisionen veroeffentlicht" % queryset.count())
publish_revision.short_description = _('Revision veroeffentlichen')
admin.site.register(Post, PostAdmin)
admin.site.register(PostRevision, PostRevisionAdmin)
| Python |
# Create your views here.
| Python |
from django.forms import ModelForm
from gironimo.gallery.models import Album, Picture
class AlbumForm(ModelForm):
class Meta:
model = Album
fields = ('name', 'content', 'category')
class PictureForm(ModelForm):
class Meta:
model = Picture
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.